7

I'm overriding hook_user_login to redirect users to a specific page when they log in. The problem is I'm using the verification email setting on registration which requires the user to set their password on first login, but I redirect them so some users aren't able to login the 2nd time to the site.

Is there something I can check in hook_user_login that will tell me if this is the first time the user has logged into the site?

6

I made a test on my test site, using the following code.

function code_testing_user_login(&$edit, $account) {
  watchdog('code_testing', 'User name: %name, user access: %access, user login: %login', array('%name' => $account->name, '%access' => $account->access, '%login' => $account->login), WATCHDOG_DEBUG);
}

I then created a test user, and logged in with that account. The code I wrote output the following message:

User name: test, user access: 0, user login: 1340038458

$account->login cannot be used because the user already logged in, when hook_user_login() is invoked. The only way to see if the user already logged in is to check $account->access.

function mymodule_user_login(&$edit, $account) {
  if ($account->access == 0) {
    // The user has never logged in before.
  }
}
  • I used if ($account->access > 0) { though as your if statement didn't seem to work – SomethingOn Jun 18 '12 at 17:07
  • That is better; $account->access should never be negative, as it is a timestamp. If its value is bigger than PHP_INT_MAX, its value would be considered negative from PHP, though. (Integers in PHP are signed, and PHP_INT_MAX is the maximum positive value they can have.) – kiamlaluno Jun 18 '12 at 17:16
  • Drupal 8 version: drupal.stackexchange.com/a/223410/45409 – oknate Dec 20 '16 at 0:12
6

Check for $account's access property. It is a timestemp the user logged in previously.

It should be other than a valid time stamp in case to be a first time login.

function MODULE_user_login(&$edit, $account){
debug($account->access);
}
0

This does not answer your question, but if I understand your scenario, this would help: don't do the redirect if the user logs in on the pass_reset page

function MYMODULE_user_login(&$edit, $account) {
    if (empty($_GET['destination'])) {
        if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {

                drupal_goto('somewhere');
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.