src/EventListener/AccessDeniedListener.php line 38

Open in your IDE?
  1. <?php
  2. /*
  3.  *  Friendu_Frontend // AccessDeniedSubscriber.php
  4.  *  
  5.  *  (c) 2018 Carsten Zeidler
  6.  */
  7. namespace App\EventListener;
  8. /**
  9.  * Description of AccessDeniedSubscriber
  10.  *
  11.  * @author Carsten
  12.  */
  13. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpFoundation\RedirectResponse;
  16. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  17. use Symfony\Component\HttpKernel\KernelEvents;
  18. use Symfony\Bundle\FrameworkBundle\Routing\Router;
  19. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  20. use Symfony\Component\Security\Http\Firewall\AccessListener;
  21. use Symfony\Component\Security\Core\Security;
  22. class AccessDeniedListener implements EventSubscriberInterface {
  23.     protected $router;
  24.     protected $security;
  25.     public function __construct(Router $routerSecurity $security) {
  26.         $this->router $router;
  27.         $this->security $security;
  28.     }
  29.     public function onKernelException(GetResponseForExceptionEvent $event): void {
  30.         $exception $event->getException();
  31.         if ($exception instanceof AccessDeniedException && !self::isThrownByFirewall($exception)) {
  32.             // Create your own response like in a custom access denied handler
  33.             if ($user $this->security->getUser() === null) {
  34.                 $response = new RedirectResponse($this->router->generate('login'));
  35.             } else {
  36.                 $response = new RedirectResponse($this->router->generate('account_home'));
  37.             }
  38.             $event->setResponse($response);
  39.             $event->stopPropagation();
  40.         }
  41.     }
  42.     public static function getSubscribedEvents() {
  43.         return [
  44.             // Define the priority to execute our subscriber before the one from the security component
  45.             KernelEvents::EXCEPTION => ['onKernelException'10000]
  46.         ];
  47.     }
  48.     /**
  49.      * Determines, by analyzing the stack trace, if an exception has been thrown by the firewall.
  50.      */
  51.     private static function isThrownByFirewall(\Throwable $exception): bool {
  52.         foreach ($exception->getTrace() as $stackItem) {
  53.             $class $stackItem['class'] ?? null;
  54.             if ($class === AccessListener::class) {
  55.                 return true;
  56.             }
  57.         }
  58.         return false;
  59.     }
  60. }