You are here

public function ContextUserAuth::switchUser in TMGMT Translator Smartling 8.4

Same name and namespace in other branches
  1. 8 src/Context/ContextUserAuth.php \Drupal\tmgmt_smartling\Context\ContextUserAuth::switchUser()
  2. 8.2 src/Context/ContextUserAuth.php \Drupal\tmgmt_smartling\Context\ContextUserAuth::switchUser()
  3. 8.3 src/Context/ContextUserAuth.php \Drupal\tmgmt_smartling\Context\ContextUserAuth::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.

bool $context_silent_user_switching:

Return value

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

Throws

\Drupal\tmgmt_smartling\Exceptions\WrongUsernameException

1 call to ContextUserAuth::switchUser()
ContextUserAuth::getCookies in src/Context/ContextUserAuth.php
Returns cookies of the needed user.

File

src/Context/ContextUserAuth.php, line 113

Class

ContextUserAuth

Namespace

Drupal\tmgmt_smartling\Context

Code

public function switchUser($name = NULL, $context_silent_user_switching = FALSE) {
  $this->logger
    ->info('We are about to switch user from "@user1" to "@user2"', [
    '@user1' => $this->account
      ->getAccountName(),
    '@user2' => $name,
  ]);
  if (empty($name) || !($account = $this->userStorage
    ->loadByProperties([
    'name' => $name,
  ]))) {
    throw new WrongUsernameException(t('User with username "@username" was not found', [
      '@username' => $name,
    ]));
  }
  $account = reset($account);

  // Call logout hooks when switching from original user.
  if (empty($context_silent_user_switching)) {
    $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.
  if (empty($context_silent_user_switching)) {
    $this->moduleHandler
      ->invokeAll('user_login', [
      $account,
    ]);
  }
  $this->logger
    ->info('User was successfully switched to "@user" on IP = "@ip"', [
    '@user' => $name,
    '@ip' => $this
      ->getIP(),
  ]);
}