src/EventListener/DynamicAccessSubscriber.php line 33

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  5. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  6. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. class DynamicAccessSubscriber implements EventSubscriberInterface
  9. {
  10.     private $checker;
  11.     private $tokenStorage;
  12.     public function __construct(AuthorizationCheckerInterface $checkerTokenStorageInterface $tokenStorage)
  13.     {
  14.         $this->checker $checker;
  15.         $this->tokenStorage $tokenStorage;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             RequestEvent::class => "onKernelRequest",
  21.         ];
  22.     }
  23.     public function onKernelRequest(RequestEvent $event)
  24.     {
  25.         if(!$event->isMasterRequest()) {
  26.             return;
  27.         }
  28.         if($this->tokenStorage->getToken() === null) {
  29.             return;
  30.         }
  31.         if($this->checker->isGranted(""$event->getRequest())) {
  32.             return;
  33.         }
  34.         $exception = new AccessDeniedException("Access Denied.");
  35.         throw $exception;
  36.     }
  37. }