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.
KernelEvents::REQUEST
and then doing something with the session is secure?