4

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
  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();
    
  • 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 '14 at 17:08

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.