src/EventListener/AuthenticationPostListener.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. use Symfony\Component\Security\Core\Security;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Symfony\Component\Routing\RouterInterface;
  9. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  10. class AuthenticationPostListener implements EventSubscriberInterface
  11. {
  12.     private $security;
  13.     private $router;
  14.     private $tokenStorage;
  15.     public function __construct(Security $securityRouterInterface $routerTokenStorageInterface $tokenStorage)
  16.     {
  17.         $this->security $security;
  18.         $this->router $router;
  19.         $this->tokenStorage $tokenStorage;
  20.     }
  21.     public static function getSubscribedEvents()
  22.     {
  23.         return [
  24.             KernelEvents::REQUEST => ['onKernelRequest'5]
  25.         ];
  26.     }
  27.     public function onKernelRequest(RequestEvent $event)
  28.     {
  29.        
  30.         $request $event->getRequest();
  31.         //dump($request->getPathInfo());
  32.         //exit;
  33.         if (in_array($request->getPathInfo(), ['/login''/login_check''/reinitialize''/logout'])) {
  34.             // Skip checks for these paths
  35.             return;
  36.         }
  37.         
  38.       
  39.         $token $this->tokenStorage->getToken();
  40.         
  41.         if ($token && $this->security->isGranted('IS_AUTHENTICATED_FULLY')) {
  42.             $user $token->getUser();
  43.             
  44.             // Check for password expiration or any other condition
  45.             if ($this->hasPasswordExpired($user->getDateMajMdp())) {
  46.                 $response = new RedirectResponse($this->router->generate('ctsweb_front_login'));
  47.                 $event->setResponse($response);
  48.                 return;
  49.             }
  50.         }
  51.     }
  52.     public function hasPasswordExpired(\DateTime $passwordUpdateDate) {
  53.         $interval date_interval_create_from_date_string("90 days");
  54.         $passwordUpdateDate $passwordUpdateDate->format('Y-m-d H:i:s');
  55.         $expirationDate date_add(new \DateTime($passwordUpdateDate), $interval);
  56.         $dateNow = (new \DateTime())->setTimezone(new \DateTimeZone('Europe/Paris'));
  57.         return $expirationDate $dateNow;
  58.     }
  59. }