ApiKeyAuthenticator::__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 0
Metric Value
cc 1
eloc 0
nc 1
nop 1
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * /src/Security/Authenticator/ApiKeyAuthenticator.php
5
 *
6
 * @author TLe, Tarmo Leppänen <[email protected]>
7
 */
8
9
namespace App\Security\Authenticator;
10
11
use App\Security\Provider\ApiKeyUserProvider;
12
use Symfony\Component\HttpFoundation\JsonResponse;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpFoundation\Response;
15
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
16
use Symfony\Component\Security\Core\Exception\AuthenticationException;
17
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
18
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
19
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
20
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
21
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
22
use function preg_match;
23
24
/**
25
 * Class ApiKeyAuthenticator
26
 *
27
 * @package App\Security\Authenticator
28
 * @author TLe, Tarmo Leppänen <[email protected]>
29
 */
30
class ApiKeyAuthenticator extends AbstractAuthenticator
31
{
32 335
    public function __construct(
33
        private readonly ApiKeyUserProvider $apiKeyUserProvider,
34
    ) {
35 335
    }
36
37 331
    public function supports(Request $request): ?bool
38
    {
39 331
        return $this->getToken($request) !== '';
40
    }
41
42 7
    public function authenticate(Request $request): Passport
43
    {
44 7
        $token = $this->getToken($request);
45 7
        $apiKey = $this->apiKeyUserProvider->getApiKeyForToken($token);
46
47 7
        if ($apiKey === null) {
48 1
            throw new UserNotFoundException('API key not found');
49
        }
50
51 6
        return new SelfValidatingPassport(new UserBadge($token));
52
    }
53
54 6
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
55
    {
56 6
        return null;
57
    }
58
59 1
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
60
    {
61 1
        $data = [
62 1
            'code' => 401,
63 1
            'message' => 'Invalid API key',
64 1
        ];
65
66 1
        return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
67
    }
68
69 333
    private function getToken(Request $request): string
70
    {
71 333
        preg_match('#^ApiKey (\w+)$#', $request->headers->get('Authorization', ''), $matches);
72
73 333
        return $matches[1] ?? '';
74
    }
75
}
76