function AccessDeniedSubscriber::onException

Same name in other branches
  1. 9 core/modules/user/src/EventSubscriber/AccessDeniedSubscriber.php \Drupal\user\EventSubscriber\AccessDeniedSubscriber::onException()
  2. 10 core/modules/user/src/EventSubscriber/AccessDeniedSubscriber.php \Drupal\user\EventSubscriber\AccessDeniedSubscriber::onException()

Redirects users when access is denied.

Parameters

\Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $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(GetResponseForExceptionEvent $event) {
    $exception = $event->getException();
    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,
            ]);
        }
        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.