Esempio n. 1
0
 /**
  * Switches to a different user.
  *
  * We don't call session_save_session() because we really want to change users.
  * Usually unsafe!
  *
  * @param string $name
  *   The username to switch to, or NULL to log out.
  *
  * @return \Symfony\Component\HttpFoundation\RedirectResponse
  *   A redirect response object.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
  */
 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>');
 }
Esempio n. 2
0
 /**
  * Switching back to previous user.
  *
  * @return bool
  *   TRUE when switched back, FALSE otherwise.
  */
 public function switchBack()
 {
     if (empty($_SESSION['masquerading'])) {
         return FALSE;
     }
     $new_user = $this->entityTypeManager->getStorage('user')->load($_SESSION['masquerading']);
     // Ensure the flag is cleared.
     unset($_SESSION['masquerading']);
     if (!$new_user) {
         return FALSE;
     }
     $account = $this->currentUser;
     // Call logout hooks when switching from masquerading user.
     $this->moduleHandler->invokeAll('user_logout', [$account]);
     // Regenerate the session ID to prevent against session fixation attacks.
     // @todo Maybe session service migrate.
     $this->sessionManager->regenerate();
     $this->currentUser->setAccount($new_user);
     \Drupal::service('session')->set('uid', $new_user->id());
     // Call all login hooks when switching back to original user.
     $this->moduleHandler->invokeAll('user_login', [$new_user]);
     $this->logger->info('User %username stopped masquerading as %old_username.', array('%username' => $new_user->getDisplayName(), '%old_username' => $account->getDisplayName(), 'link' => $this->l($this->t('view'), $new_user->toUrl())));
     return TRUE;
 }