I set up my session in my request kernel event listener where I update a last_seen
session variable like this:
class RequestListener
{
public $session;
public function __construct( Session $session ) {
//leave blank
$this->session=$session;
}
public function onKernelRequest( GetResponseEvent $event ) {
if ( HttpKernel::MASTER_REQUEST != $event->getRequestType() ) {
// don't do anything if it's not the master request
return;
}
else {
$session = $this->session;
$current_time = time();
//if they're logged in and it hasn't been more than an hour since their last request
if ( $session->get( 'auth' ) ) {
if ( ( (int) $session->get( 'last_seen' ) ) > ( $current_time - 10 ) ) {//timeout: half hour (temporarily changed to ten seconds)
//regenerate session ID:
$session->migrate();
}
else {
//destroy session
$session->invalidate();//shortcut for clear() & then migrate()
//set session variable to acknowledge timeout
$session->getFlashBag()->add( 'info', 'You were automatically logged out due to inactivity' );
}
$session->set( 'last_seen', $current_time );
}
else {
$session->set( 'last_seen', $current_time );
}
}
}
}
This code is ran for every request. As you can see, the flashbag info flash message is set to hold You were automatically logged out due to inactivity
, but this never displays.
My Twig template:
I know there should be nothing wrong with this because I see other flashes in other situations.
{# START info messages #}
{% set info_messages = app.session.flashbag.get('info') %}
{% if info_messages is defined and info_messages is not empty%}
<div class="row alert alert-info alert-block">
<ul>
{% for info_message in info_messages %}
<li>{{info_message | raw}}</li>
{% endfor %}
</ul>
</div>
{% endif %}
{# END info messages #}
So the flow I've been testing is this:
- The user comes to the login page
- Submit login form (refreshes the login route)
- Login is deemed successful, redirected to another page (let's say page B)
- Wait ten seconds and refresh
- Kernel event should clear the session and add the item to the flashbag
- When the controller for page B's route is reached, it checks the session to see if the user is logged in and then redirects to the login page because they're not
- Login page simply renders twig template, no flash can be seen
Does this have something to do with flash message auto-expiration which is briefly mentioned in the documentation?
I suspect this is a simple session issue, possibly impacted by the redirects and or auto-expiration.
Edit
I've also tried changing my onKernelRequest function so that it runs the session handling code for really every request (removed MASTER_REQUEST
check)
Edit 2
I've tried using $session->setFlash('info', '...message...')
instead of $session->getFlashBag()->add(...)
in my listener & controller and app.session.flashes('info')
instead of app.session.flashbag.get('info')
in my template as suggested in the #symfony IRC channel but still no luck.