src/EventSubscriber/BetaAccessSubscriber.php line 38

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.         'app_login',
  16.         'app_logout',
  17.         '_wdt',
  18.         '_profiler',
  19.     ];
  20.     public function __construct(
  21.         private Security $security,
  22.         private RouterInterface $router,
  23.         private \App\Service\BetaCookie $betaCookie,
  24.         private array $betaHosts
  25.     ) {}
  26.     public static function getSubscribedEvents(): array
  27.     {
  28.         return [
  29.             KernelEvents::REQUEST => ['onKernelRequest'10],
  30.         ];
  31.     }
  32.     public function onKernelRequest(RequestEvent $event): void
  33.     {
  34.         if (!$event->isMainRequest()) {
  35.             return;
  36.         }
  37.         $request $event->getRequest();
  38.         if (!in_array($request->getHost(), $this->betaHoststrue)) {
  39.             return;
  40.         }
  41.         $route $request->attributes->get('_route');
  42.         if (in_array($routeself::ALLOWED_ROUTEStrue)) {
  43.             return;
  44.         }
  45.         if ($this->security->getUser() !== null) {
  46.             return;
  47.         }
  48.         // Cookie signé : l'ancienne valeur « true », forgeable, n'est plus acceptée.
  49.         if ($this->betaCookie->isValid($request)) {
  50.             return;
  51.         }
  52.         $event->setResponse(
  53.             new RedirectResponse($this->router->generate('beta_request'))
  54.         );
  55.     }
  56. }