Total Complexity | 5 |
Total Lines | 32 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 0 |
1 | <?php |
||
16 | class AuthenticationMiddleware implements MiddlewareInterface |
||
17 | { |
||
18 | public function __construct(private readonly UserRepository $userRepository) |
||
|
|||
19 | { |
||
20 | } |
||
21 | |||
22 | /** |
||
23 | * Load current user from session if exists and still valid. |
||
24 | */ |
||
25 | 3 | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
26 | { |
||
27 | /** @var SessionInterface $session */ |
||
28 | 3 | $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE); |
|
29 | |||
30 | 3 | if ($session->has('user')) { |
|
31 | 2 | $user = $this->userRepository->getOneById($session->get('user')); |
|
32 | |||
33 | 2 | if ($user) { |
|
34 | 1 | User::setCurrent($user); |
|
35 | } |
||
36 | |||
37 | // If we were supposed to be logged in, but the user is not available anymore, that means the user |
||
38 | // was forcibly logged out (likely deleted), so we clear his entire session |
||
39 | 2 | if (!User::getCurrent()) { |
|
40 | 1 | $session->clear(); |
|
41 | } |
||
42 | } |
||
43 | |||
44 | 3 | return $handler->handle($request); |
|
45 | } |
||
46 | } |
||
47 |