src/Security/SessionIdleHandler.php line 42
<?php
namespace App\Security;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class SessionIdleHandler
{
private RequestStack $requestStack;
private TokenStorageInterface $securityToken;
private RouterInterface $router;
private $maxIdleTime;
public function __construct($maxIdleTime, RequestStack $requestStack, TokenStorageInterface $securityToken, RouterInterface $router)
{
$this->requestStack = $requestStack;
$this->securityToken = $securityToken;
$this->router = $router;
$this->maxIdleTime = $maxIdleTime;
}
public function onKernelRequest(RequestEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST != $event->getRequestType()) {
return;
}
if ($this->maxIdleTime > 0) {
$session = $this->requestStack->getSession();
$session->start();
$lapse = time() - $session->getMetadataBag()->getLastUsed();
if ($lapse > $this->maxIdleTime) {
$this->securityToken->setToken(null);
$event->setResponse(new RedirectResponse($this->router->generate('app_logout'))); // or whatever route you need
}
}
}
}