ApplicationAuthenticator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 0
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 2
ccs 1
cts 1
cp 1
crap 1
rs 10
1
<?php
2
3
namespace App\Security;
4
5
use App\Repository\ApplicationRepositoryInterface;
6
use Symfony\Component\HttpFoundation\JsonResponse;
7
use Symfony\Component\HttpFoundation\Request;
8
use Symfony\Component\HttpFoundation\Response;
9
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
10
use Symfony\Component\Security\Core\Exception\AuthenticationException;
11
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
12
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
13
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
14
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
15
16
class ApplicationAuthenticator extends AbstractAuthenticator {
17
18
    public const HEADER_KEY = 'X-Token';
19
20
    public function __construct(private ApplicationRepositoryInterface $repository)
21 13
    {
22 13
    }
23 13
24
    /**
25
     * @inheritDoc
26
     */
27
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response {
28 1
        return new JsonResponse([
29 1
            'success' => false,
30 1
            'message' => sprintf('Authentication failed: %s', $exception->getMessage())
31 1
        ], Response::HTTP_FORBIDDEN);
32 1
    }
33
34
    /**
35
     * @inheritDoc
36
     */
37
    public function supports(Request $request): bool {
38 1
        return $request->headers->has(static::HEADER_KEY);
39 1
    }
40 1
41
    /**
42 1
     * @inheritDoc
43
     */
44
    public function authenticate(Request $request): Passport {
45
        $token = $request->headers->get(static::HEADER_KEY);
46
        $application = $this->repository->findOneByApiKey($token);
47
48 3
        if($application === null) {
49 3
            throw new AuthenticationException('Invalid API key');
50
        }
51
52
        return new SelfValidatingPassport(
53
            new UserBadge($token, fn($token) => $this->repository->findOneByApiKey($token))
54
        );
55 2
    }
56
57 2
    /**
58
     * @inheritDoc
59
     */
60
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response {
61
        return null;
62
    }
63
}