3 namespace Drupal\user\EventSubscriber;
5 use Drupal\Core\Session\AccountInterface;
6 use Drupal\Core\Routing\RouteMatch;
7 use Drupal\Core\Routing\UrlGeneratorTrait;
8 use Drupal\Core\Routing\UrlGeneratorInterface;
9 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
10 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
11 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
12 use Symfony\Component\HttpKernel\KernelEvents;
15 * Redirects users when access is denied.
17 * Anonymous users are taken to the login page when attempting to access the
18 * user profile pages. Authenticated users are redirected from the login form to
19 * their profile page and from the user registration form to their profile edit
22 class AccessDeniedSubscriber implements EventSubscriberInterface {
24 use UrlGeneratorTrait;
29 * @var \Drupal\Core\Session\AccountInterface
34 * Constructs a new redirect subscriber.
36 * @param \Drupal\Core\Session\AccountInterface $account
38 * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
41 public function __construct(AccountInterface $account, UrlGeneratorInterface $url_generator) {
42 $this->account = $account;
43 $this->setUrlGenerator($url_generator);
47 * Redirects users when access is denied.
49 * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
50 * The event to process.
52 public function onException(GetResponseForExceptionEvent $event) {
53 $exception = $event->getException();
54 if ($exception instanceof AccessDeniedHttpException) {
55 $route_name = RouteMatch::createFromRequest($event->getRequest())->getRouteName();
56 if ($this->account->isAuthenticated()) {
57 switch ($route_name) {
59 // Redirect an authenticated user to the profile page.
60 $event->setResponse($this->redirect('entity.user.canonical', ['user' => $this->account->id()]));
64 // Redirect an authenticated user to the profile form.
65 $event->setResponse($this->redirect('entity.user.edit_form', ['user' => $this->account->id()]));
69 elseif ($route_name === 'user.page') {
70 $event->setResponse($this->redirect('user.login'));
78 public static function getSubscribedEvents() {
79 // Use a higher priority than
80 // \Drupal\Core\EventSubscriber\ExceptionLoggingSubscriber, because there's
81 // no need to log the exception if we can redirect.
82 $events[KernelEvents::EXCEPTION][] = ['onException', 75];