You are here

function masquerade_switch_user_validate in Masquerade 8.2

Validates whether the current user can masquerade as a given target user.

Use this function to generate user-friendly error messages to show in the user interface.

Parameters

\Drupal\user\UserInterface $target_account: The user account object to masquerade as.

Return value

string|null A string containing a validation error message, or NULL if the current user can masquerade as $target_account.

2 calls to masquerade_switch_user_validate()
MasqueradeForm::validateForm in src/Form/MasqueradeForm.php
Form validation handler.
SwitchController::switchTo in src/Controller/SwitchController.php
Masquerades the current user as a given user.

File

./masquerade.module, line 223
Allows privileged users to masquerade as another user.

Code

function masquerade_switch_user_validate(UserInterface $target_account) {
  $user = \Drupal::currentUser();
  if (\Drupal::service('masquerade')
    ->isMasquerading()) {
    return t('You are masquerading already. Please <a href="@unmasquerade-url">switch back</a> to your account to masquerade as another user.', [
      '@unmasquerade-url' => Url::fromRoute('masquerade.unmasquerade')
        ->toString(),
    ]);
  }
  if ($target_account
    ->id() == $user
    ->id()) {
    return t('You cannot masquerade as yourself. Please choose a different user to masquerade as.');
  }
  if (\Drupal::config('system.maintenance')
    ->get('enabled') && !$target_account
    ->hasPermission('access site in maintenance mode')) {
    return t('@user is not permitted to %permission. <a href=":maintenance-url">Disable maintenance mode</a> to masquerade as @user.', [
      '@user' => $target_account
        ->getDisplayName(),
      '%permission' => t('Use the site in maintenance mode'),
      ':maintenance-url' => Url::fromRoute('system.site_maintenance_mode')
        ->toString(),
    ]);
  }
  if (!masquerade_target_user_access($target_account)) {
    return t('You are not allowed to masquerade as %name.', [
      '%name' => $target_account
        ->getDisplayName(),
    ]);
  }
}