src/EventListener/AccessDeniedListener.php line 51

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Psr\Log\LoggerInterface;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  9. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  10. class AccessDeniedListener implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * @var TokenStorageInterface
  14.      */
  15.     private $tokenStorage;
  16.     /**
  17.      * @var LoggerInterface
  18.      */
  19.     private $logger;
  20.     /**
  21.      * @param TokenStorageInterface $tokenStorage
  22.      * @param LoggerInterface $logger
  23.      */
  24.     public function __construct(TokenStorageInterface $tokenStorageLoggerInterface $logger)
  25.     {
  26.         $this->tokenStorage $tokenStorage;
  27.         $this->logger $logger;
  28.     }
  29.     /**
  30.      * @return array[]
  31.      */
  32.     public static function getSubscribedEvents(): array
  33.     {
  34.         return [
  35.             // the priority must be greater than the Security HTTP
  36.             // ExceptionListener, to make sure it's called before
  37.             // the default exception listener
  38.             KernelEvents::EXCEPTION => ['onKernelException'2],
  39.         ];
  40.     }
  41.     /**
  42.      * @param ExceptionEvent $event
  43.      */
  44.     public function onKernelException(ExceptionEvent $event): void
  45.     {
  46.         $exception $event->getThrowable();
  47.         if (!$exception instanceof AccessDeniedException) {
  48.             return;
  49.         }
  50.         $token $this->tokenStorage->getToken();
  51.         $user  is_null($token) ? null $token->getUser();
  52.         $userIdentifier  is_null($user) ? '' $user->getUserIdentifier();
  53.         $roles  is_null($token) ? [] : $token->getRoleNames();
  54.         $this->logger->error('Accès denied.', [
  55.             'url' => $event->getRequest()->getPathInfo(),
  56.             'user' => $userIdentifier,
  57.             'isAuthenticated' => !is_null($user),
  58.             'roles' => $roles,
  59.         ]);
  60.     }
  61. }