src/Event/TwoFactorListener.php line 30
<?php
declare(strict_types=1);
namespace App\Event;
use App\Controller\SecurityController;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
use function str_contains;
class TwoFactorListener implements EventSubscriberInterface
{
public function __construct(
private readonly RouterInterface $router,
private readonly string $env,
) {
}
public static function getSubscribedEvents(): array
{
return [
RequestEvent::class => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $event): void
{
if ($this->env !== 'prod') {
return;
}
$route = $event->getRequest()->get('_route');
if (!$route || str_contains((string) $route, 'admin') === false) {
return;
}
$session = $event->getRequest()->getSession();
if (!$session->get(SecurityController::SESSION_2FA_KEY)) {
$event->setResponse(new RedirectResponse($this->router->generate('app_twofactor')));
}
}
}