JWTCommonListener::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
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
}