You are here

public function TfaLoginController::accessSelfOrAdmin in Two-factor Authentication (TFA) 8

Checks that current user is selected user or is admin.

Parameters

\Drupal\Core\Routing\RouteMatchInterface $route: The route to be checked.

\Drupal\Core\Session\AccountInterface $account: The current user.

Return value

\Drupal\Core\Access\AccessResult The access result.

1 call to TfaLoginController::accessSelfOrAdmin()
TfaLoginController::access in src/Controller/TfaLoginController.php
Denies access unless user matches hash value.
1 string reference to 'TfaLoginController::accessSelfOrAdmin'
tfa.routing.yml in ./tfa.routing.yml
tfa.routing.yml

File

src/Controller/TfaLoginController.php, line 71

Class

TfaLoginController
Provides access control on the verification form.

Namespace

Drupal\tfa\Controller

Code

public function accessSelfOrAdmin(RouteMatchInterface $route, AccountInterface $account) {
  $target_user = $route
    ->getParameter('user');

  // Start with a positive access result that can be cached based on the
  // current route, which includes both route name and parameters.
  $access = AccessResult::allowed();
  $access
    ->addCacheContexts([
    'route',
  ]);
  if (!$target_user instanceof UserInterface) {
    return $access
      ->andIf(AccessResult::forbidden('Invalid user.'));
  }

  // Before we perform any checks that are dependent on the current user, make
  // the result dependent on the current user. If we were just checking perms
  // here, we could rely on user.permissions, but in this case we are also
  // dependent on the ID of the user, which requires the higher level user
  // context.
  $access
    ->addCacheableDependency($account);
  if (!$account
    ->isAuthenticated()) {
    return $access
      ->andIf(AccessResult::forbidden('User is not logged in.'));
  }
  $is_self = $account
    ->id() === $target_user
    ->id();
  $is_admin = $account
    ->hasPermission('administer users');
  $is_self_or_admin = AccessResult::allowedIf($is_self || $is_admin);
  return $access
    ->andIf($is_self_or_admin);
}