|
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
|
|
|
} |