src/EventSubscriber/PasswordChangeSubscriber.php line 32

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