You are here

protected function Masquerade::switchUser in Masquerade 8.2

Logs out current user and logs in as pointed user.

Parameters

\Drupal\user\UserInterface $user: The user entity to switch to.

Return value

\Drupal\user\UserInterface The previous user entity.

See also

\Drupal\Core\Session\SessionHandler::write()

\Drupal\user\Authentication\Provider\Cookie::getUserFromSession()

2 calls to Masquerade::switchUser()
Masquerade::switchBack in src/Masquerade.php
Switching back to previous user.
Masquerade::switchTo in src/Masquerade.php
Masquerades the current user as a given user.

File

src/Masquerade.php, line 110

Class

Masquerade
Defines a masquerade service to switch user account.

Namespace

Drupal\masquerade

Code

protected function switchUser(UserInterface $user) {

  /** @var \Drupal\user\UserInterface $previous */
  $previous = $this->userStorage
    ->load($this->currentUser
    ->id());

  // Call logout hooks when switching from original user.
  $this->moduleHandler
    ->invokeAll('user_logout', [
    $previous,
  ]);

  // Regenerate the session ID to prevent against session fixation attacks.
  $this->sessionManager
    ->regenerate();

  // Supposed "safe" user switch method https://www.drupal.org/node/218104
  // @todo Use `Drupal::service('account_switcher')` but care about session.
  $this->currentUser
    ->setAccount($user);
  $this->session
    ->set('uid', $user
    ->id());

  // Call all login hooks when making user login.
  $this->moduleHandler
    ->invokeAll('user_login', [
    $user,
  ]);
  return $previous;
}