|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Application\Middleware; |
|
6
|
|
|
|
|
7
|
|
|
use Mezzio\Session\SessionMiddleware; |
|
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
10
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
11
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Middleware that writes to the session if a user is connected, |
|
15
|
|
|
* in order to refresh the mtime of the session file. |
|
16
|
|
|
* |
|
17
|
|
|
* If the Mezzio setting non_locking is set to true (i.e., PHP's read_and_close()), |
|
18
|
|
|
* the session may be garbage collected even if it was accessed within gc_maxlifetime. |
|
19
|
|
|
* This happens because PHP relies on the mtime of the session file, |
|
20
|
|
|
* which is updated only when the session is written. |
|
21
|
|
|
* |
|
22
|
|
|
* As a result, users may be randomly logged out. |
|
23
|
|
|
* |
|
24
|
|
|
* So as long as the user is connected, we write an arbitrary data to the |
|
25
|
|
|
* session to update the mtime of the file to prevent its garbage collection. |
|
26
|
|
|
*/ |
|
27
|
|
|
class RefreshSessionTimestampMiddleware implements MiddlewareInterface |
|
28
|
|
|
{ |
|
29
|
1 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
30
|
|
|
{ |
|
31
|
1 |
|
$session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE); |
|
32
|
|
|
|
|
33
|
1 |
|
if ($session->has('user')) { |
|
34
|
|
|
// Setting a value to trigger session write. |
|
35
|
|
|
// Harmless if set twice by concurrent requests. |
|
36
|
1 |
|
$session->set('_last_access', time()); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
1 |
|
return $handler->handle($request); |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|