0

I'm trying to create a custom login form, since I need it to be ajax based. And I can't use the existing modules that do this. So far I have achieved this by setting the global $user object to the loaded user and calling user_login_finalize(). But now I need to make the login persist and I have no idea how the default drupal login does it. Any tips are appreciated. Thanks

UPDATE:

The duplicate question indicated by Pontus Nilsson does not mention in any way how to make the login persist nor how to use the default drupal remember me or the RememberMe module functionality.

UPDATE 2:

I must elaborate that I have installed Remember Me module to make the persistent login optional for the user. Is that a reason why I needed to go through all this hassle explained in my answer to make the programmatical login persist?

1

This is how I accomplished the remember me feature. Since I didn't find any specific resources on this matter, the proposed solution may or may not be optimal and correct, although it works fine.

You use the following code to login a user programmatically:

$user = user_load($uid);
$login_array = array ('name' => $user_first_query->name);
user_login_finalize($login_array);

After that you have to decide whether to persist the login or not using the provided check box in the login form:

//at this point we need to persist the login by saving the user again
//with the remember_me data. But doing so, resets the user picture.
//So we need to preserve it somehow.
$user_picture_id = $user->picture;
if($_POST['remember_me']) {
    user_save($user, array('data' => array('remember_me' => (int)$_POST['remember_me'])));
}
else {
    unset($user->data['remember_me']);
    user_save($user, array());
}

//restore the user picture id
db_update('users')
    ->fields(array(
         'picture' => $user_picture_id,
    ))
    ->condition('uid', $uid)
    ->execute();

For the part where I have done unset($user->data['remember_me']); I have made sure that the rememeber_me data does not exist from a previous login. I think this should be done in the modulename_user_presave() hook but I couldn't implement it there.

Remember that since the main question is how to persist a user login, I have not provided a full login procedure, for example you should authenticate the user's credentials using the user_authenticate() function.

| improve this answer | |

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.