Last active
May 21, 2019 19:20
-
-
Save bbene/c3bb05daa092780c016f9ee96a15db62 to your computer and use it in GitHub Desktop.
Symfony 3 Auto Logout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
parameters: | |
# ... | |
session_max_idle_time: 450 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ... | |
app.handler.session_idle: | |
class: AppBundle\Handler\SessionIdleHandler | |
arguments: ["@session", "@security.token_storage", "@router", "%session_max_idle_time%"] | |
tags: | |
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// AppBundle/Handler/SessionIdleHandler.php | |
namespace AppBundle\Handler; | |
use Symfony\Component\HttpFoundation\RedirectResponse; | |
use Symfony\Component\HttpFoundation\Session\SessionInterface; | |
use Symfony\Component\HttpKernel\Event\GetResponseEvent; | |
use Symfony\Component\HttpKernel\HttpKernelInterface; | |
use Symfony\Component\Routing\RouterInterface; | |
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; | |
class SessionIdleHandler | |
{ | |
protected $session; | |
protected $tokenStorage; | |
protected $router; | |
protected $maxIdleTime; | |
public function __construct( | |
SessionInterface $session, | |
TokenStorageInterface $tokenStorage, | |
RouterInterface $router, | |
$maxIdleTime = 0 | |
) { | |
$this->session = $session; | |
$this->tokenStorage = $tokenStorage; | |
$this->router = $router; | |
$this->maxIdleTime = $maxIdleTime; | |
} | |
public function onKernelRequest(GetResponseEvent $event) | |
{ | |
if (HttpKernelInterface::MASTER_REQUEST != $event->getRequestType()) { | |
return; | |
} | |
if ($this->maxIdleTime > 0) { | |
$this->session->start(); | |
$lapse = time() - $this->session->getMetadataBag()->getLastUsed(); | |
if ($lapse > $this->maxIdleTime && null !== $this->tokenStorage->getToken()) { | |
$this->tokenStorage->setToken(null); | |
// Change the route if you are not using FOSUserBundle. | |
$event->setResponse(new RedirectResponse($this->router->generate('fos_user_security_login'))); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
and you can clear session data with
$this->session->clear();
into the last condition.