LicenseListener   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 21
c 0
b 0
f 0
dl 0
loc 50
rs 10
wmc 13

2 Methods

Rating   Name   Duplication   Size   Complexity  
C onKernelRequest() 0 40 12
A __construct() 0 6 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AtlassianConnectBundle\Listener;
6
7
use AtlassianConnectBundle\Entity\TenantInterface;
8
use Symfony\Component\HttpFoundation\RedirectResponse;
9
use Symfony\Component\HttpKernel\Event\RequestEvent;
10
use Symfony\Component\Routing\RouterInterface;
11
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
12
13
class LicenseListener
14
{
15
    public function __construct(
16
        private RouterInterface $router,
17
        private TokenStorageInterface $tokenStorage,
18
        private string $environment,
19
        private array $licenseAllowList
20
    ) {
21
    }
22
23
    public function onKernelRequest(RequestEvent $event): void
24
    {
25
        if (!$event->isMainRequest()) {
26
            return;
27
        }
28
29
        $request = $event->getRequest();
30
        $route = $request->attributes->get('_route');
31
32
        if (null !== $route && false === $request->attributes->get('requires_license', false)) {
33
            return;
34
        }
35
36
        if ('active' === $request->query->get('lic') || 'prod' !== $this->environment) {
37
            return;
38
        }
39
40
        // Checking for allowed users
41
        try {
42
            /** @var TenantInterface $user */
43
            $user = $this->tokenStorage->getToken()->getUser();
44
45
            if ($user instanceof TenantInterface && $user->isWhiteListed()) {
46
                return;
47
            }
48
49
            $today = date('Y-m-d');
50
51
            foreach ($this->licenseAllowList as $allowed) {
52
                if ($today <= $allowed['valid_till'] && $allowed['client_key'] === $user->getClientKey()) {
53
                    return;
54
                }
55
            }
56
        } catch (\Throwable $e) {
57
            // Do nothing
58
        }
59
60
        $url = $this->router->generate('atlassian_connect_unlicensed', $request->query->all());
61
        $response = new RedirectResponse($url);
62
        $event->setResponse($response);
63
    }
64
}
65