src/Event/TwoFactorListener.php line 30

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Event;
  4. use App\Controller\SecurityController;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\Routing\RouterInterface;
  9. use function str_contains;
  10. class TwoFactorListener implements EventSubscriberInterface
  11. {
  12.     public function __construct(
  13.         private readonly RouterInterface $router,
  14.         private readonly string $env,
  15.     ) {
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             RequestEvent::class => 'onKernelRequest',
  21.         ];
  22.     }
  23.     public function onKernelRequest(RequestEvent $event): void
  24.     {
  25.         if ($this->env !== 'prod') {
  26.             return;
  27.         }
  28.         $route $event->getRequest()->get('_route');
  29.         if (!$route || str_contains((string) $route'admin') === false) {
  30.             return;
  31.         }
  32.         $session $event->getRequest()->getSession();
  33.         if (!$session->get(SecurityController::SESSION_2FA_KEY)) {
  34.             $event->setResponse(new RedirectResponse($this->router->generate('app_twofactor')));
  35.         }
  36.     }
  37. }