<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\User;
use Psr\Log\LoggerInterface;
use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\Email\Generator\CodeGeneratorInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Security;
class TwoFactorResendSubscriber implements EventSubscriberInterface
{
protected $logger;
protected $security;
protected $codeGenerator;
protected $router;
public function __construct(
LoggerInterface $logger,
Security $security,
CodeGeneratorInterface $codeGenerator,
RouterInterface $router
) {
$this->logger = $logger;
$this->security = $security;
$this->codeGenerator = $codeGenerator;
$this->router = $router;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [['onKernelRequest', 4]],
];
}
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
if ($request->getPathInfo() !== '/2fa/resend') {
return;
}
$this->logger->debug('***** TwoFactorResendSubscriber: resend request intercepted');
$user = $this->security->getUser();
if (!$user instanceof User) {
$this->logger->debug('***** TwoFactorResendSubscriber: no valid user, redirecting to login');
$event->setResponse(new RedirectResponse($this->router->generate('app_login')));
return;
}
$this->codeGenerator->generateAndSend($user);
$this->logger->debug('***** TwoFactorResendSubscriber: new code generated and sent');
$event->setResponse(new RedirectResponse($this->router->generate('2fa_login') . '?resent=1'));
}
}