src/EventListener/SessionIdleListener.php line 55

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\Routing\RouterInterface;
  8. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  9. use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
  10. use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
  11. class SessionIdleListener
  12. {
  13.     /**
  14.      * @var int
  15.      */
  16.     private $maxIdleTime;
  17.     /**
  18.      * @var AuthorizationChecker
  19.      */
  20.     private $authChecker;
  21.     /**
  22.      * @var TokenStorageInterface
  23.      */
  24.     private $tokenStorage;
  25.     /**
  26.      * @var SessionInterface
  27.      */
  28.     protected $session;
  29.     /**
  30.      * @var RouterInterface
  31.      */
  32.     protected $router;
  33.     public function __construct(
  34.         string $maxIdleTime,
  35.         AuthorizationChecker $authChecker,
  36.         TokenStorageInterface $tokenStorage,
  37.         SessionInterface $session,
  38.         RouterInterface $router
  39.     ) {
  40.         $this->maxIdleTime = (int) $maxIdleTime;
  41.         $this->authChecker $authChecker;
  42.         $this->tokenStorage $tokenStorage;
  43.         $this->session $session;
  44.         $this->router $router;
  45.     }
  46.     public function onKernelRequest(RequestEvent $event): void
  47.     {
  48.         if (!$event->isMasterRequest()
  49.             || $this->maxIdleTime <= 0
  50.             || $this->isAuthenticatedAnonymously()) {
  51.             return;
  52.         }
  53.         $this->session->start();
  54.         if ((time() - $this->session->getMetadataBag()->getLastUsed()) <= $this->maxIdleTime) {
  55.             return;
  56.         }
  57.         $this->tokenStorage->setToken(null);
  58.         /** @var FlashBag $flashBag */
  59.         $flashBag $this->session->getBag('flashes');
  60.         $flashBag->set('info'"Vous avez été déconnecté pour cause d'inactivité.");
  61.         $this->session->invalidate();
  62.         $event->setResponse(new RedirectResponse($this->router->generate('app_login')));
  63.     }
  64.     private function isAuthenticatedAnonymously(): bool
  65.     {
  66.         return !$this->tokenStorage->getToken()
  67.             || !$this->authChecker->isGranted(AuthenticatedVoter::IS_AUTHENTICATED_FULLY);
  68.     }
  69. }