src/EventSubscriber/TwoFactorResendSubscriber.php line 43

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use App\Entity\User;
  5. use Psr\Log\LoggerInterface;
  6. use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\Email\Generator\CodeGeneratorInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\RedirectResponse;
  9. use Symfony\Component\HttpKernel\Event\RequestEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. use Symfony\Component\Routing\RouterInterface;
  12. use Symfony\Component\Security\Core\Security;
  13. class TwoFactorResendSubscriber implements EventSubscriberInterface
  14. {
  15. protected $logger;
  16. protected $security;
  17. protected $codeGenerator;
  18. protected $router;
  19. public function __construct(
  20. LoggerInterface $logger,
  21. Security $security,
  22. CodeGeneratorInterface $codeGenerator,
  23. RouterInterface $router
  24. ) {
  25. $this->logger = $logger;
  26. $this->security = $security;
  27. $this->codeGenerator = $codeGenerator;
  28. $this->router = $router;
  29. }
  30. public static function getSubscribedEvents(): array
  31. {
  32. return [
  33. KernelEvents::REQUEST => [['onKernelRequest', 4]],
  34. ];
  35. }
  36. public function onKernelRequest(RequestEvent $event): void
  37. {
  38. $request = $event->getRequest();
  39. if ($request->getPathInfo() !== '/2fa/resend') {
  40. return;
  41. }
  42. $this->logger->debug('***** TwoFactorResendSubscriber: resend request intercepted');
  43. $user = $this->security->getUser();
  44. if (!$user instanceof User) {
  45. $this->logger->debug('***** TwoFactorResendSubscriber: no valid user, redirecting to login');
  46. $event->setResponse(new RedirectResponse($this->router->generate('app_login')));
  47. return;
  48. }
  49. $this->codeGenerator->generateAndSend($user);
  50. $this->logger->debug('***** TwoFactorResendSubscriber: new code generated and sent');
  51. $event->setResponse(new RedirectResponse($this->router->generate('2fa_login') . '?resent=1'));
  52. }
  53. }