function AccessDeniedSubscriber::onException

Same name and namespace in other branches
  1. 9 core/modules/user/src/EventSubscriber/AccessDeniedSubscriber.php \Drupal\user\EventSubscriber\AccessDeniedSubscriber::onException()
  2. 8.9.x core/modules/user/src/EventSubscriber/AccessDeniedSubscriber.php \Drupal\user\EventSubscriber\AccessDeniedSubscriber::onException()
  3. 10 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 (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.