src/EventListener/ControlListener.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpFoundation\RedirectResponse;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\Routing\RouterInterface;
  6. use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
  7. use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
  8. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  9. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  10. use Symfony\Component\Security\Core\Security;
  11. /**
  12.  * Access Control Listener
  13.  */
  14. final class ControlListener
  15. {
  16.     /** @var RouterInterface $router */
  17.     private $router;
  18.     /** @var Security $security */
  19.     private $security;
  20.     public function __construct(RouterInterface $routerSecurity $security)
  21.     {
  22.         $this->router $router;
  23.         $this->security $security;
  24.     }
  25.     public function onAccessController(RequestEvent $event)
  26.     {
  27.         $request $event->getRequest();
  28.         $routeCollec $this->router->getRouteCollection();
  29.         $token $this->security->getToken();
  30.         // https://symfony.com/doc/current/routing.html#getting-the-route-name-and-parameters
  31.         $routeName $request->attributes->get('_route');
  32.         $activeRoute $routeCollec->get($routeName ?? '');
  33.         $securedRoute false// Verification pour la prĂ©sence ou non en session du activeStructure
  34.         if ($activeRoute) {
  35.             $roles $activeRoute->getRequirements();
  36.             if (isset($roles['role'])) {
  37.                 if (false === $this->security->isGranted($roles['role'])) {
  38.                     throw new AccessDeniedException();
  39.                 }
  40.             }
  41.             // Tokens instances implementing the getFirewallName method
  42.             if (!(
  43.                 $token instanceof PreAuthenticatedToken
  44.             ||  $token instanceof RememberMeToken
  45.             ||  $token instanceof UsernamePasswordToken
  46.             )) {
  47.                 return;
  48.             }
  49.             if ('factuwall' === $token->getFirewallName()
  50.             &&  $activeRoute->getPath() != '/' && $activeRoute->getPath() != '/structure/set/'
  51.             ) {
  52.                 $securedRoute true;
  53.             }
  54.             if ($securedRoute === true && !$request->getSession()->get('activeStructure')) {
  55.                 $url $this->router->generate('factu_homepage');
  56.                 $event->setResponse(new RedirectResponse($url));
  57.             }
  58.         }
  59.     }
  60. }