-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiTokenAuthenticator.php
More file actions
164 lines (132 loc) · 5.22 KB
/
ApiTokenAuthenticator.php
File metadata and controls
164 lines (132 loc) · 5.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
<?php
namespace SyncEngine\Security;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\IpUtils;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use SyncEngine\Repository\ApiTokenRepository;
use SyncEngine\Repository\UserRepository;
class ApiTokenAuthenticator extends AbstractAuthenticator
{
public function __construct(
#[Autowire( '%env(SYNCENGINE_API_TOKEN_HEADER)%' )]
private readonly ?string $header,
private readonly UserRepository $userRepository,
private readonly ApiTokenRepository $apiTokenRepository,
protected readonly LoggerInterface $syncengineLogger,
) {}
public function supports( Request $request ): ?bool
{
return str_starts_with( $request->getPathInfo(), '/api/' );
}
public function authenticate( Request $request ): Passport
{
if ( empty( $this->header ) ) {
$authorization = $request->headers->get( 'Authorization' );
// Bearer token.
$apiToken = substr( $authorization, 7 );
} else {
$apiToken = $request->headers->get( $this->header );
}
if ( empty($apiToken) ) {
throw new CustomUserMessageAuthenticationException( 'No API Token provided' );
}
$validate = function ( $apiToken ) use ( $request ) {
$user = $this->userRepository->findByApiToken( $apiToken );
if ( ! $user ) {
throw new UserNotFoundException();
}
if ( ! $this->isTokenValid( $apiToken, $request ) ) {
throw new CustomUserMessageAuthenticationException( 'Invalid API Token' );
}
return $user;
};
return new SelfValidatingPassport( new UserBadge( $apiToken, $validate ) );
}
public function isTokenValid( $apiToken, Request $request ): bool
{
$token = $this->apiTokenRepository->findOneBy( [ 'token' => $apiToken ] );
if ( new \DateTime() > $token->getExpires() ) {
throw new CustomUserMessageAuthenticationException( 'Expired API Token' );
}
$config = $token->getConfig();
if ( empty( $config['restrictions'] ) ) {
return true;
}
try {
$restrictions = $config['restrictions'];
$ips = $restrictions['ip'] ?? '';
if ( $ips && $ips = array_map( 'trim', explode( ',', $ips ) ) ) {
$ip = $request->getClientIp();
if ( ! IpUtils::checkIp( $ip, $ips ) ) {
return false;
}
}
$hosts = $restrictions['host'] ?? '';
if ( $hosts && $hosts = array_map( 'trim', explode( ',', $hosts ) ) ) {
$host = $request->headers->get( 'origin' ) ?: $request->headers->get( 'HTTP_ORIGIN' );
if ( ! $host || ! is_string( $host ) ) {
return in_array( 'localhost', $hosts ) && IpUtils::isPrivateIp( $request->getClientIp() );
}
if ( ! $this->validateHost( $host, $hosts ) ) {
return false;
}
}
} catch ( \Exception $e ) {
$this->syncengineLogger->error( $e );
// Do not provide further information to the client, further info can be found in the logs
throw new AuthenticationException();
}
return true;
}
public function validateHost( string $host, array $allowedHosts ): bool
{
// Normalize domain to ensure it doesn't have a leading protocol.
$parsedHost = parse_url( $host, PHP_URL_HOST ) ?: $host;
foreach ( $allowedHosts as $allowedHost ) {
if ( strcasecmp( $parsedHost, $allowedHost ) === 0 ) {
return true;
}
// Handle host wildcards (e.g., *.example.com).
if ( str_starts_with( $allowedHost, '*' ) ) {
$pattern = str_replace( '.', '\.', ltrim( $allowedHost, '*' ) );
$pattern = '/^([a-z0-9-]+\.)?' . $pattern . '$/i';
if ( preg_match( $pattern, $parsedHost ) ) {
return true;
}
}
}
return false;
}
public function onAuthenticationSuccess( Request $request, TokenInterface $token, string $firewallName ): ?Response
{
return null;
}
public function onAuthenticationFailure( Request $request, AuthenticationException $exception ): ?Response
{
$data = [
'message' => strtr( $exception->getMessageKey(), $exception->getMessageData() ),
];
return new JsonResponse( $data, Response::HTTP_UNAUTHORIZED );
}
// public function start(Request $request, AuthenticationException $authException = null): Response
// {
// /*
// * If you would like this class to control what happens when an anonymous user accesses a
// * protected page (e.g. redirect to /login), uncomment this method and make this class
// * implement Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface.
// *
// * For more details, see https://symfony.com/doc/current/security/experimental_authenticators.html#configuring-the-authentication-entry-point
// */
// }
}