<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
class MfaSubscriber implements EventSubscriberInterface
{
private Security $security;
private UrlGeneratorInterface $urlGenerator;
public function __construct(Security $security, UrlGeneratorInterface $urlGenerator)
{
$this->security = $security;
$this->urlGenerator = $urlGenerator;
}
public static function getSubscribedEvents(): array
{
return [
'kernel.request' => ['onKernelRequest', -10], // prioridad más baja
];
}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
$currentRoute = $request->attributes->get('_route');
// Evitar bucle infinito redirigiendo sobre la misma ruta
if ($currentRoute === 'enable_mfa' || $currentRoute === 'app_login' || $currentRoute === 'save_qr_code' || $currentRoute === 'generate_qr_code') {
return;
}
$user = $this->security->getUser();
if (!$user) {
return;
}
$mandatoryMfa = false;
if (
($user->getPartner() && $user->getPartner()->isMandatoryMfa()) ||
($user->getCustomer() && $user->getCustomer()->isMandatoryMfa()) ||
($user->getWholesaler() && $user->getWholesaler()->isMandatoryMfa())
) {
$mandatoryMfa = true;
}
if (($user->isMandatoryMfa() || $mandatoryMfa) && !$user->isGoogleAuthenticatorEnabled()) {
$event->setResponse(new RedirectResponse(
$this->urlGenerator->generate('enable_mfa')
));
}
}
}