You are here

public function SwitchUserController::switchUser in Devel 8

Same name and namespace in other branches
  1. 8.3 src/Controller/SwitchUserController.php \Drupal\devel\Controller\SwitchUserController::switchUser()
  2. 8.2 src/Controller/SwitchUserController.php \Drupal\devel\Controller\SwitchUserController::switchUser()
  3. 4.x src/Controller/SwitchUserController.php \Drupal\devel\Controller\SwitchUserController::switchUser()

Switches to a different user.

We don't call session_save_session() because we really want to change users. Usually unsafe!

Parameters

string $name: The username to switch to, or NULL to log out.

Return value

\Symfony\Component\HttpFoundation\RedirectResponse A redirect response object.

Throws

\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException

1 string reference to 'SwitchUserController::switchUser'
devel.routing.yml in ./devel.routing.yml
devel.routing.yml

File

src/Controller/SwitchUserController.php, line 96

Class

SwitchUserController
Controller for switch to another user account.

Namespace

Drupal\devel\Controller

Code

public function switchUser($name = NULL) {
  if (empty($name) || !($account = $this->userStorage
    ->loadByProperties([
    'name' => $name,
  ]))) {
    throw new AccessDeniedHttpException();
  }
  $account = reset($account);

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

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

  // Based off masquarade module as:
  // https://www.drupal.org/node/218104 doesn't stick and instead only
  // keeps context until redirect.
  $this->account
    ->setAccount($account);
  $this->session
    ->set('uid', $account
    ->id());

  // Call all login hooks when switching to masquerading user.
  $this->moduleHandler
    ->invokeAll('user_login', [
    $account,
  ]);
  return $this
    ->redirect('<front>');
}