src/EventSubscriber/KernelSubscriber.php line 59

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use App\Service\UserService;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Routing\RouterInterface;
  10. use Symfony\Component\Security\Core\Security;
  11. class KernelSubscriber implements EventSubscriberInterface
  12. {
  13.     public const TWO_FACTOR_ROUTE 'two_factor_confirm';
  14.     public const LOGIN_ROUTE 'login';
  15.     public const HOME_ROUTE 'home';
  16.     public const VALIDATE_ROUTE 'two_factor_validate';
  17.     private const OPEN_ROUTES = [
  18.         self::TWO_FACTOR_ROUTE,
  19.         self::LOGIN_ROUTE,
  20.         self::VALIDATE_ROUTE
  21.     ];
  22.     /** @var Security $security */
  23.     private $security;
  24.     /** @var RouterInterface $router */
  25.     private $router;
  26.     /** @var UserService $userService */
  27.     private $userService;
  28.     /**
  29.      * KernelSubscriber constructor.
  30.      * @param Security $security
  31.      * @param RouterInterface $router
  32.      * @param UserService $userService
  33.      */
  34.     public function __construct(Security $securityRouterInterface $routerUserService $userService)
  35.     {
  36.         $this->security $security;
  37.         $this->router $router;
  38.         $this->userService $userService;
  39.     }
  40.     /**
  41.      * @return array
  42.      */
  43.     public static function getSubscribedEvents(): array
  44.     {
  45.         return [
  46.             KernelEvents::REQUEST => 'onKernelRequest'
  47.         ];
  48.     }
  49.     /**
  50.      * @param RequestEvent $event
  51.      */
  52.     public function onKernelRequest(RequestEvent $event)
  53.     {
  54.         if (!$event->isMasterRequest()) {
  55.             return;
  56.         }
  57.         if ($this->security->getUser()) {
  58.             $user $this->security->getUser();
  59.             if ($user instanceof User) {
  60.                 $route $event->getRequest()->get('_route');
  61.                 if (
  62.                     $this->userService->isAdmin($user) &&
  63.                     $user->getTwoFactorToken() && !in_array($routeself::OPEN_ROUTES)
  64.                 ) {
  65.                     $event->setResponse(new RedirectResponse($this->router->generate(self::TWO_FACTOR_ROUTE)));
  66.                 }
  67.             }
  68.         }
  69.     }
  70. }