src/EventSubscriber/MfaSubscriber.php line 28

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  7. use Symfony\Component\Security\Core\Security;
  8. class MfaSubscriber implements EventSubscriberInterface
  9. {
  10.     private Security $security;
  11.     private UrlGeneratorInterface $urlGenerator;
  12.     public function __construct(Security $securityUrlGeneratorInterface $urlGenerator)
  13.     {
  14.         $this->security $security;
  15.         $this->urlGenerator $urlGenerator;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             'kernel.request' => ['onKernelRequest', -10], // prioridad más baja
  21.         ];
  22.     }
  23.     public function onKernelRequest(RequestEvent $event): void
  24.     {
  25.         if (!$event->isMainRequest()) {
  26.             return;
  27.         }
  28.         $request $event->getRequest();
  29.         $currentRoute $request->attributes->get('_route');
  30.         // Evitar bucle infinito redirigiendo sobre la misma ruta
  31.         if ($currentRoute === 'enable_mfa' || $currentRoute === 'app_login' || $currentRoute === 'save_qr_code' || $currentRoute === 'generate_qr_code') {
  32.             return;
  33.         }
  34.     
  35.         $user $this->security->getUser();
  36.         if (!$user) {
  37.             return;
  38.         }
  39.         $mandatoryMfa false;
  40.         if (
  41.             ($user->getPartner() && $user->getPartner()->isMandatoryMfa()) ||
  42.             ($user->getCustomer() && $user->getCustomer()->isMandatoryMfa()) ||
  43.             ($user->getWholesaler() && $user->getWholesaler()->isMandatoryMfa())
  44.         ) {
  45.             $mandatoryMfa true;
  46.         }
  47.         if (($user->isMandatoryMfa() || $mandatoryMfa) && !$user->isGoogleAuthenticatorEnabled()) {
  48.             $event->setResponse(new RedirectResponse(
  49.                 $this->urlGenerator->generate('enable_mfa')
  50.             ));
  51.         }
  52.     }
  53. }