You are here

public function AccessDeniedSubscriber::onException in Drupal 9

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

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 47

Class

AccessDeniedSubscriber
Redirects users when access is denied.

Namespace

Drupal\user\EventSubscriber

Code

public function onException(ExceptionEvent $event) {
  $exception = $event
    ->getThrowable();
  if ($exception instanceof AccessDeniedHttpException) {
    $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 ($route_name === 'user.logout') {
      $redirect_url = Url::fromRoute('<front>', [], [
        'absolute' => TRUE,
      ]);
    }
    if ($redirect_url) {
      $event
        ->setResponse(new RedirectResponse($redirect_url
        ->toString()));
    }
  }
}