src/EventSubscriber/BetaAccessSubscriber.php line 39

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Component\Routing\RouterInterface;
  8. use Symfony\Component\Security\Core\Security;
  9. class BetaAccessSubscriber implements EventSubscriberInterface
  10. {
  11.     private const ALLOWED_ROUTES = [
  12.         'beta_request',
  13.         'beta_access_request',
  14.         'confirm_email',
  15.         'beta_direct_access',
  16.         'app_login',
  17.         'app_logout',
  18.         '_wdt',
  19.         '_profiler',
  20.     ];
  21.     public function __construct(
  22.         private Security $security,
  23.         private RouterInterface $router,
  24.         private \App\Service\BetaCookie $betaCookie,
  25.         private array $betaHosts
  26.     ) {}
  27.     public static function getSubscribedEvents(): array
  28.     {
  29.         return [
  30.             KernelEvents::REQUEST => ['onKernelRequest'10],
  31.         ];
  32.     }
  33.     public function onKernelRequest(RequestEvent $event): void
  34.     {
  35.         if (!$event->isMainRequest()) {
  36.             return;
  37.         }
  38.         $request $event->getRequest();
  39.         if (!in_array($request->getHost(), $this->betaHoststrue)) {
  40.             return;
  41.         }
  42.         $route $request->attributes->get('_route');
  43.         if (in_array($routeself::ALLOWED_ROUTEStrue)) {
  44.             return;
  45.         }
  46.         if ($this->security->getUser() !== null) {
  47.             return;
  48.         }
  49.         // Cookie signé : l'ancienne valeur « true », forgeable, n'est plus acceptée.
  50.         if ($this->betaCookie->isValid($request)) {
  51.             return;
  52.         }
  53.         $event->setResponse(
  54.             new RedirectResponse($this->router->generate('beta_request'))
  55.         );
  56.     }
  57. }