src/Handler/SessionIdleHandler.php line 56

Open in your IDE?
  1. <?php
  2. namespace App\Handler;
  3. use Symfony\Component\HttpFoundation\RedirectResponse;
  4. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\HttpKernelInterface;
  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. /**
  11.  * Class SessionIdleHandler
  12.  * @package App\Handler
  13.  */
  14. class SessionIdleHandler
  15. {
  16.     protected $session;
  17.     protected $tokenStorage;
  18.     protected $router;
  19.     protected $maxIdleTime;
  20.     protected $authorizationChecker;
  21.     /**
  22.      * SessionIdleHandler constructor.
  23.      * @param SessionInterface $session
  24.      * @param TokenStorageInterface $tokenStorage
  25.      * @param RouterInterface $router
  26.      * @param AuthorizationChecker $authorizationChecker
  27.      * @param int $maxIdleTime
  28.      */
  29.     public function __construct(
  30.         SessionInterface $session,
  31.         TokenStorageInterface $tokenStorage,
  32.         RouterInterface $router,
  33.         AuthorizationChecker $authorizationChecker,
  34.         $maxIdleTime 0
  35.     ) {
  36.         $this->session $session;
  37.         $this->tokenStorage $tokenStorage;
  38.         $this->router $router;
  39.         $this->maxIdleTime $maxIdleTime;
  40.         $this->authorizationChecker $authorizationChecker;
  41.     }
  42.     /**
  43.      * @param RequestEvent $event
  44.      */
  45.     public function onKernelRequest(RequestEvent $event)
  46.     {
  47.         if (HttpKernelInterface::MASTER_REQUEST != $event->getRequestType()) {
  48.             return;
  49.         }
  50.         if ($this->maxIdleTime 0) {
  51.             $this->session->start();
  52.             $lapse time() - $this->session->getMetadataBag()->getLastUsed();
  53.             if ($lapse $this->maxIdleTime && $this->authorizationChecker->isGranted('ROLE_USER')) {
  54.                 $this->tokenStorage->setToken(null);
  55.                 $event->setResponse(
  56.                     new RedirectResponse(
  57.                         $this->router->generate(
  58.                             'security_login',
  59.                             ['session_idle' => true]
  60.                         )
  61.                     )
  62.                 );
  63.             }
  64.         }
  65.     }
  66. }