src/EventSubscriber/PasswordExpirationManager.php line 33

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  9. use Symfony\Component\Security\Core\Security;
  10. class PasswordExpirationManager implements EventSubscriberInterface
  11. {
  12.     private $security;
  13.     private $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 => [
  23.                 ['forcePasswordChange'0]
  24.             ],
  25.         ];
  26.     }
  27.     public function forcePasswordChange(RequestEvent $event): void
  28.     {
  29.         // only deal with the main request, disregard subrequests
  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 User) {
  36.             return;
  37.         }
  38.         // if it's not their first login, and they do not need to change their password, move on
  39.          $now_date strtotime(date("Y-m-d H:i:s"));
  40.         $pastChange_date strtotime($user->getLastPasswordChange());
  41.         //dd($pastChange_date);
  42.         $timePassed abs($now_date $pastChange_date)/(60 60 24);
  43.         //dd($timePassed);
  44.         if ($user->getForcePasswordChange() == && $timePassed 90) {
  45.             return;
  46.         }
  47.         // if we get here, it means we need to redirect them to the password change view.
  48.         $redirectTo $this->urlGenerator->generate('app_reset_password_no_token');
  49.         if ($event->getRequest()->getRequestUri() != $redirectTo){
  50.             $event->setResponse(new RedirectResponse($redirectTo));
  51.         }
  52.         return;
  53.     }
  54. }