Chris@0: account = $account; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Redirects users when access is denied. Chris@0: * Chris@0: * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event Chris@0: * The event to process. Chris@0: */ Chris@0: public function onException(GetResponseForExceptionEvent $event) { Chris@0: $exception = $event->getException(); Chris@0: if ($exception instanceof AccessDeniedHttpException) { Chris@0: $route_name = RouteMatch::createFromRequest($event->getRequest())->getRouteName(); Chris@18: $redirect_url = NULL; Chris@0: if ($this->account->isAuthenticated()) { Chris@0: switch ($route_name) { Chris@0: case 'user.login'; Chris@0: // Redirect an authenticated user to the profile page. Chris@18: $redirect_url = Url::fromRoute('entity.user.canonical', ['user' => $this->account->id()], ['absolute' => TRUE]); Chris@0: break; Chris@0: Chris@0: case 'user.register'; Chris@0: // Redirect an authenticated user to the profile form. Chris@18: $redirect_url = Url::fromRoute('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE]); Chris@0: break; Chris@0: } Chris@0: } Chris@0: elseif ($route_name === 'user.page') { Chris@18: $redirect_url = Url::fromRoute('user.login', [], ['absolute' => TRUE]); Chris@18: } Chris@18: Chris@18: if ($redirect_url) { Chris@18: $event->setResponse(new RedirectResponse($redirect_url->toString())); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public static function getSubscribedEvents() { Chris@0: // Use a higher priority than Chris@0: // \Drupal\Core\EventSubscriber\ExceptionLoggingSubscriber, because there's Chris@0: // no need to log the exception if we can redirect. Chris@0: $events[KernelEvents::EXCEPTION][] = ['onException', 75]; Chris@0: return $events; Chris@0: } Chris@0: Chris@0: }