6

A service I have takes a username, and should find and log in a local Drupal user account with that username. After logging in, I need the session ID (from the sessions table) for that users new session.

I have some basic procedural code that I'd like to refactor for Drupal 8 practices:

$user = user_load_by_name($username);
if ($user) {
  user_login_finalize($user);
}

1) What's the OO way of loading a user entity? A service I found that may help loading a user is entity.manager, but is that the right way to do it?

2) Logging a user in? Should I just take the code from user_login_finalize and try and inject the services used and essentially "copy" what's done in that function?

3) After the user is logged in, how can I get their session information? Injecting the current_user service doesn't work, because the user data in there is stale after I log the user in.

EDIT: Looks like a user's session is not saved until AuthenticationSubscriber runs (listens for kernel response event), which is when the session data would be saved. Maybe I can manually save the session before then, and then obtain session? Not sure what that would impact.

2
  • Hi, I'm having the same problem and can't find a solution, so I was wondering a) if either you managed to resolve it, and b) if not, do you think waiting for a KernelEvents::REQUEST and then doing something with the session is secure?
    – Ynhockey
    Dec 11, 2019 at 16:40
  • Core's user_login_finalize stores the session right away now. So you can extract it from the session service immediately after calling that function. I asked this question when working on a D8 port of the CAS module. See git.drupalcode.org/project/cas/blob/8.x-1.x/src/Service/…
    – Brian
    Dec 12, 2019 at 17:19

1 Answer 1

1
  1. For general entity, yes you can use entity.manager service.

    For user entity, you can use \Drupal\user\Entity\User. However in your case, you are going to load user by username, this can't be done by User Entity class, you have to use entity.manager.

    user_load_by_name will call something like this:

    $entity_manager = Drupal::service('entity.manager');
    $user = $entity_manager->storage('user')->loadByProperties(array('name' => $nusername));
    
  2. I will just use this function if there is no reason to replace it.

  3. Use the session_manager service.

    $session_manager = Drupal::service('session_manager');
    $session_id = $session_manager->getId();
    
1
  • 1
    Unfortunately I cannot use session_manager because the it seems the session for the newly logged in user isn't persisted until AuthenticationSubscriber runs (see my edit)
    – Brian
    Oct 1, 2014 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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