JWTCommonListener   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Test Coverage

Coverage 76.92%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 29
ccs 10
cts 13
cp 0.7692
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A onAuthenticatedAccess() 0 4 1
A __construct() 0 3 1
A onAuthenticatedResponse() 0 10 4
1
<?php
2
3
namespace App\Infrastructure\Security;
4
5
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTAuthenticatedEvent;
6
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
7
use Symfony\Component\HttpKernel\Event\ResponseEvent;
8
use Symfony\Component\Security\Core\User\UserInterface;
9
10
/**
11
 * This Listener will work for REST Calls from every Module
12
 * and will automatically renew the Tokens that are about to be expired.
13
 * This should prevent the logging-out of an active user without UI having to explicitly renew the Token.
14
 */
15
class JWTCommonListener
16
{
17
    use JWTBaseListener;
18
19
    const REFRESH_TIME = 1800;
20
    private ?array $payload = null;
21
    private ?UserInterface $user = null;
22
23 15
    public function __construct(
24
        private JWTTokenManagerInterface $jwtManager)
25
    {
26 15
    }
27
28 7
    public function onAuthenticatedAccess(JWTAuthenticatedEvent $event)
29
    {
30 7
        $this->payload = $event->getPayload();
31 7
        $this->user = $event->getToken()->getUser();
32 7
    }
33
34 15
    public function onAuthenticatedResponse(ResponseEvent $event)
35
    {
36 15
        if ($this->payload != null && $this->user != null) {
37 7
            $expireTime = $this->payload['exp'] - time();
38 7
            if ($expireTime < static::REFRESH_TIME) {
39
                // Refresh token
40
                $jwt = $this->jwtManager->create($this->user);
41
                $response = $event->getResponse();
42
                // Set cookie
43
                $this->createCookie($response, $jwt);
44
            }
45
        }
46
    }
47
}