vendor/eckinox/security-bundle/src/EventSubscriber/PasswordChangeSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. namespace Eckinox\SecurityBundle\EventSubscriber;
  3. use App\Entity\Security\AppUser;
  4. use App\Entity\Security\User;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  10. use Symfony\Component\Security\Core\Security;
  11. class PasswordChangeSubscriber implements EventSubscriberInterface
  12. {
  13.     private Security $security;
  14.     private UrlGeneratorInterface $urlGenerator;
  15.     public function __construct(Security $securityUrlGeneratorInterface $urlGenerator)
  16.     {
  17.         $this->security $security;
  18.         $this->urlGenerator $urlGenerator;
  19.     }
  20.     public static function getSubscribedEvents(): array
  21.     {
  22.         return [
  23.             KernelEvents::REQUEST => [['forcePasswordChange'0]],
  24.         ];
  25.     }
  26.     public function forcePasswordChange(RequestEvent $event): void
  27.     {
  28.         $route $event->getRequest()->get('_route');
  29.         
  30.         if (!$event->isMainRequest()) {
  31.             return;
  32.         }
  33.         $user $this->security->getUser();
  34.         // if you do not have a valid user, it means it's not an authenticated request, so it's not our concern
  35.         if ($user instanceof AppUser) {
  36.             $route "eckinox_security_app_user_create_password";
  37.             $twoFARoute 'eckinox_app_2fa_login';
  38.         } elseif ($user instanceof User) {
  39.             $route "eckinox_security_user_create_password";
  40.             $twoFARoute 'eckinox_2fa_login';
  41.         } else {
  42.             return;    
  43.         }
  44.         if($event->getRequest()->get('_route') === $twoFARoute) {
  45.             return;
  46.         }
  47.         // if we are visiting the password change route, no need to redirect
  48.         // otherwise we'd create an infinite redirection loop
  49.         if ($event->getRequest()->get('_route') === $route) {
  50.             return;
  51.         }
  52.         // if it's not their first login, and they do not need to change their password, move on
  53.         if (!$user->isPasswordChangeRequired()) {
  54.             return;
  55.         }
  56.         // if we get here, it means we need to redirect them to the password change view.
  57.         $event->setResponse(new RedirectResponse($this->urlGenerator->generate($route)));
  58.     }
  59. }
  60. ?>