In hook_user_login is there a way to know if this is the first time the user has logged in?

by SomethingOn   Last Updated January 11, 2018 10:07 AM

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?

Tags : 7 users


Answers 4


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);
}
Shoaib Nawaz
Shoaib Nawaz
June 18, 2012 16:35 PM

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.
  }
}
kiamlaluno
kiamlaluno
June 18, 2012 17:01 PM

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');
        }
    }
}
commonpike
commonpike
November 10, 2015 20:35 PM

Instead of using $account->access == 0, use $account->access == REQUEST_TIME.

user82217
user82217
January 11, 2018 09:49 AM

Related Questions




Create A Sort Features In Drupal

Updated April 04, 2015 15:03 PM

Generating user accounts programatically

Updated April 22, 2015 07:03 AM

Can admins create new accounts without passwords?

Updated February 21, 2016 01:03 AM