src/EventSubscriber/ForceChangePasswordSubscriber.php line 38

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Consultant;
  4. use App\Entity\User;
  5. use App\Service\Entity\ConsultantService;
  6. use Symfony\Component\Console\Logger\ConsoleLogger;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\HttpKernel\Event\RequestEvent;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  12. use Symfony\Component\Security\Core\Security;
  13. class ForceChangePasswordSubscriber implements EventSubscriberInterface
  14. {
  15.     private $security;
  16.     private $urlGenerator;
  17.     private $consultantService;
  18.     public function __construct(Security $securityUrlGeneratorInterface $urlGeneratorConsultantService $consultantService)
  19.     {
  20.         $this->security $security;
  21.         $this->urlGenerator $urlGenerator;
  22.         $this->consultantService $consultantService;
  23.     }
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [
  27.             KernelEvents::REQUEST => [
  28.                 ['forcePasswordChange'0]
  29.             ],
  30.         ];
  31.     }
  32.     public function forcePasswordChange(RequestEvent $event): void
  33.     {
  34.         // only deal with the main request, disregard subrequests
  35.         if (!$event->isMainRequest()) {
  36.             return;
  37.         }
  38.         $user $this->security->getUser();
  39.         // if you do not have a valid user, it means it's not an authenticated request, so it's not our concern
  40.         if (!$user instanceof User) {
  41.             return;
  42.         }
  43.         if (!$user instanceof Consultant || !$this->consultantService->consultantNeedToResetPassword($user)) {
  44.             return;
  45.         }
  46.         // if we get here, it means we need to redirect them to the password change view.
  47.         $redirectTo $this->urlGenerator->generate('changepassword');
  48.         if ($event->getRequest()->getRequestUri() != $redirectTo) {
  49.             $event->setResponse(new RedirectResponse($redirectTo));
  50.         }
  51.     }
  52. }