function AccessDeniedSubscriber::on403

Same name and namespace in other branches
  1. 11.x core/modules/user/src/EventSubscriber/AccessDeniedSubscriber.php \Drupal\user\EventSubscriber\AccessDeniedSubscriber::on403()

Redirects users when access is denied.

Parameters

\Symfony\Component\HttpKernel\Event\ExceptionEvent $event: The event to process.

File

core/modules/user/src/EventSubscriber/AccessDeniedSubscriber.php, line 62

Class

AccessDeniedSubscriber
Redirects users when access is denied.

Namespace

Drupal\user\EventSubscriber

Code

public function on403(ExceptionEvent $event) : void {
  $route_name = RouteMatch::createFromRequest($event->getRequest())
    ->getRouteName();
  $redirect_url = NULL;
  if ($this->account
    ->isAuthenticated()) {
    switch ($route_name) {
      case 'user.login':
        // Redirect an authenticated user to the profile page.
        $redirect_url = Url::fromRoute('entity.user.canonical', [
          'user' => $this->account
            ->id(),
        ], [
          'absolute' => TRUE,
        ]);
        break;

      case 'user.register':
        // Redirect an authenticated user to the profile form.
        $redirect_url = Url::fromRoute('entity.user.edit_form', [
          'user' => $this->account
            ->id(),
        ], [
          'absolute' => TRUE,
        ]);
        break;

    }
  }
  elseif ($route_name === 'user.page') {
    $redirect_url = Url::fromRoute('user.login', [], [
      'absolute' => TRUE,
    ]);
  }
  elseif (in_array($route_name, [
    'user.logout',
    'user.logout.confirm',
  ], TRUE)) {
    $redirect_url = Url::fromRoute('<front>', [], [
      'absolute' => TRUE,
    ]);
  }
  if ($redirect_url) {
    $event->setResponse(new RedirectResponse($redirect_url->toString()));
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.