-
Notifications
You must be signed in to change notification settings - Fork 133
/
Copy pathJWT.php
304 lines (258 loc) · 8.01 KB
/
JWT.php
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Shield\Authentication\Authenticators;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\AuthenticationException;
use CodeIgniter\Shield\Authentication\AuthenticatorInterface;
use CodeIgniter\Shield\Authentication\JWTManager;
use CodeIgniter\Shield\Config\Auth;
use CodeIgniter\Shield\Config\AuthJWT;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Shield\Exceptions\RuntimeException;
use CodeIgniter\Shield\Models\TokenLoginModel;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Shield\Result;
use InvalidArgumentException;
use stdClass;
/**
* Stateless JWT Authenticator
*/
class JWT implements AuthenticatorInterface
{
/**
* @var string Special ID Type.
* This Authenticator is stateless, so no `auth_identities` record.
*/
public const ID_TYPE_JWT = 'jwt';
protected AuthJWT $authJWTConfig;
protected ?User $user = null;
protected JWTManager $jwtManager;
protected TokenLoginModel $tokenLoginModel;
protected ?stdClass $payload = null;
/**
* @var string The key group. The array key of Config\AuthJWT::$keys.
*/
protected $keyset = 'default';
/**
* @param UserModel $provider The persistence engine
*/
public function __construct(
protected UserModel $provider,
) {
$this->authJWTConfig = config('AuthJWT');
$this->jwtManager = service('jwtmanager');
$this->tokenLoginModel = model(TokenLoginModel::class);
}
/**
* Attempts to authenticate a user with the given $credentials.
* Logs the user in with a successful check.
*
* @param array{token?: string} $credentials
*/
public function attempt(array $credentials): Result
{
/** @var IncomingRequest $request */
$request = service('request');
$ipAddress = $request->getIPAddress();
$userAgent = (string) $request->getUserAgent();
$result = $this->check($credentials);
if (! $result->isOK()) {
if ($this->authJWTConfig->recordLoginAttempt >= Auth::RECORD_LOGIN_ATTEMPT_FAILURE) {
// Record a failed login attempt.
$this->tokenLoginModel->recordLoginAttempt(
self::ID_TYPE_JWT,
$credentials['token'] ?? '',
false,
$ipAddress,
$userAgent,
);
}
return $result;
}
$user = $result->extraInfo();
if ($user->isBanned()) {
if ($this->authJWTConfig->recordLoginAttempt >= Auth::RECORD_LOGIN_ATTEMPT_FAILURE) {
// Record a banned login attempt.
$this->tokenLoginModel->recordLoginAttempt(
self::ID_TYPE_JWT,
'sha256:' . hash('sha256', $credentials['token'] ?? ''),
false,
$ipAddress,
$userAgent,
$user->id,
);
}
$this->user = null;
return new Result([
'success' => false,
'reason' => $user->getBanMessage() ?? lang('Auth.bannedUser'),
]);
}
$this->login($user);
if ($this->authJWTConfig->recordLoginAttempt === Auth::RECORD_LOGIN_ATTEMPT_ALL) {
// Record a successful login attempt.
$this->tokenLoginModel->recordLoginAttempt(
self::ID_TYPE_JWT,
'sha256:' . hash('sha256', $credentials['token']),
true,
$ipAddress,
$userAgent,
$this->user->id,
);
}
return $result;
}
/**
* Checks a user's $credentials to see if they match an
* existing user.
*
* In this case, $credentials has only a single valid value: token,
* which is the plain text token to return.
*
* @param array{token?: string} $credentials
*/
public function check(array $credentials): Result
{
if (! array_key_exists('token', $credentials) || $credentials['token'] === '') {
return new Result([
'success' => false,
'reason' => lang(
'Auth.noToken',
[$this->authJWTConfig->authenticatorHeader],
),
]);
}
// Check JWT
try {
$this->payload = $this->jwtManager->parse($credentials['token'], $this->keyset);
} catch (RuntimeException $e) {
return new Result([
'success' => false,
'reason' => $e->getMessage(),
]);
}
$userId = $this->payload->sub ?? null;
if ($userId === null) {
return new Result([
'success' => false,
'reason' => 'Invalid JWT: no user_id',
]);
}
// Find User
$user = $this->provider->findById($userId);
if ($user === null) {
return new Result([
'success' => false,
'reason' => lang('Auth.invalidUser'),
]);
}
return new Result([
'success' => true,
'extraInfo' => $user,
]);
}
/**
* Checks if the user is currently logged in.
* Since AccessToken usage is inherently stateless,
* it runs $this->attempt on each usage.
*/
public function loggedIn(): bool
{
if ($this->user !== null) {
return true;
}
/** @var IncomingRequest $request */
$request = service('request');
$token = $this->getTokenFromRequest($request);
return $this->attempt([
'token' => $token,
])->isOK();
}
/**
* Gets token from Request.
*/
public function getTokenFromRequest(RequestInterface $request): string
{
assert($request instanceof IncomingRequest);
$tokenHeader = $request->getHeaderLine(
$this->authJWTConfig->authenticatorHeader ?? 'Authorization',
);
if (str_starts_with($tokenHeader, 'Bearer')) {
return trim(substr($tokenHeader, 6));
}
return $tokenHeader;
}
/**
* Logs the given user in by saving them to the class.
*/
public function login(User $user): void
{
$this->user = $user;
}
/**
* Logs a user in based on their ID.
*
* @param int|string $userId
*
* @throws AuthenticationException
*/
public function loginById($userId): void
{
$user = $this->provider->findById($userId);
if ($user === null) {
throw AuthenticationException::forInvalidUser();
}
$this->login($user);
}
/**
* Logs the current user out.
*/
public function logout(): void
{
$this->user = null;
}
/**
* Returns the currently logged in user.
*/
public function getUser(): ?User
{
return $this->user;
}
/**
* Updates the user's last active date.
*/
public function recordActiveDate(): void
{
if (! $this->user instanceof User) {
throw new InvalidArgumentException(
__METHOD__ . '() requires logged in user before calling.',
);
}
$this->user->last_active = Time::now();
$this->provider->save($this->user);
}
/**
* @param string $keyset The key group. The array key of Config\AuthJWT::$keys.
*/
public function setKeyset($keyset): void
{
$this->keyset = $keyset;
}
/**
* Returns payload
*/
public function getPayload(): ?stdClass
{
return $this->payload;
}
}