-
Notifications
You must be signed in to change notification settings - Fork 112
/
JWTGuard.php
609 lines (534 loc) · 12.5 KB
/
JWTGuard.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
<?php
/*
* This file is part of jwt-auth.
*
* (c) 2014-2021 Sean Tymon <tymon148@gmail.com>
* (c) 2021 PHP Open Source Saver
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPOpenSourceSaver\JWTAuth;
use Illuminate\Auth\Events\Attempting;
use Illuminate\Auth\Events\Authenticated;
use Illuminate\Auth\Events\Failed;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;
use Illuminate\Auth\GuardHelpers;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Http\Request;
use Illuminate\Support\Traits\Macroable;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
use PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException;
use PHPOpenSourceSaver\JWTAuth\Exceptions\UserNotDefinedException;
/**
* @mixin JWT
*/
class JWTGuard implements Guard
{
use GuardHelpers {
setUser as guardHelperSetUser;
}
use Macroable {
__call as macroCall;
}
/**
* The user we last attempted to retrieve.
*
* @var Authenticatable
*/
protected $lastAttempted;
/**
* The JWT instance.
*
* @var JWT
*/
protected $jwt;
/**
* The request instance.
*
* @var Request
*/
protected $request;
/**
* The event dispatcher instance.
*
* @var Dispatcher
*/
protected $events;
/**
* The name of the Guard.
*
* @var string
*/
protected $name = 'tymon.jwt';
/**
* Instantiate the class.
*
* @return void
*/
public function __construct(JWT $jwt, UserProvider $provider, Request $request, Dispatcher $eventDispatcher)
{
$this->jwt = $jwt;
$this->provider = $provider;
$this->request = $request;
$this->events = $eventDispatcher;
}
/**
* Get the currently authenticated user.
*
* @return Authenticatable|null
*/
public function user()
{
if (null !== $this->user) {
return $this->user;
}
if (
$this->jwt->setRequest($this->request)->getToken()
&& ($payload = $this->jwt->check(true))
&& $this->validateSubject()
) {
return $this->user = $this->provider->retrieveById($payload['sub']);
}
}
/**
* @return int|string|null
*/
public function getUserId()
{
if (null !== $this->user) {
return $this->user->getAuthIdentifier();
}
if (
$this->jwt->setRequest($this->request)->getToken()
&& ($payload = $this->jwt->check(true))
&& $this->validateSubject()
) {
return $payload['sub'];
}
return null;
}
/**
* Get the currently authenticated user or throws an exception.
*
* @return Authenticatable
*
* @throws UserNotDefinedException
*/
public function userOrFail()
{
if (!$user = $this->user()) {
throw new UserNotDefinedException();
}
return $user;
}
/**
* Validate a user's credentials.
*
* @return bool
*/
public function validate(array $credentials = [])
{
return (bool) $this->attempt($credentials, false);
}
/**
* Attempt to authenticate the user using the given credentials and return the token.
*
* @param bool $login
*
* @return bool|string
*/
public function attempt(array $credentials = [], $login = true)
{
$this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
$this->fireAttemptEvent($credentials);
if ($this->hasValidCredentials($user, $credentials)) {
return $login ? $this->login($user) : true;
}
$this->fireFailedEvent($user, $credentials);
return false;
}
/**
* Create a token for a user.
*
* @return string
*/
public function login(JWTSubject $user)
{
$token = $this->jwt->fromUser($user);
$this->setToken($token)->setUser($user);
$this->fireLoginEvent($user);
return $token;
}
/**
* Logout the user, thus invalidating the token.
*
* @param bool $forceForever
*
* @return void
*/
public function logout($forceForever = false)
{
try {
$this->requireToken()->invalidate($forceForever);
} catch (JWTException $e) {
// Proceed with the logout as normal if we can't invalidate the token
}
$this->fireLogoutEvent($this->user);
$this->user = null;
$this->jwt->unsetToken();
}
/**
* Refresh the token.
*
* @param bool $forceForever
* @param bool $resetClaims
*
* @return string
*/
public function refresh($forceForever = false, $resetClaims = false)
{
return $this->requireToken()->refresh($forceForever, $resetClaims);
}
/**
* Invalidate the token.
*
* @param bool $forceForever
*
* @return JWT
*/
public function invalidate($forceForever = false)
{
return $this->requireToken()->invalidate($forceForever);
}
/**
* Create a new token by User id.
*
* @return string|null
*/
public function tokenById($id)
{
if ($user = $this->provider->retrieveById($id)) {
return $this->jwt->fromUser($user);
}
}
/**
* Log a user into the application using their credentials.
*
* @return bool
*/
public function once(array $credentials = [])
{
if ($this->validate($credentials)) {
$this->setUser($this->lastAttempted);
return true;
}
return false;
}
/**
* Log the given User into the application.
*
* @return bool
*/
public function onceUsingId($id)
{
if ($user = $this->provider->retrieveById($id)) {
$this->setUser($user);
return true;
}
return false;
}
/**
* Alias for onceUsingId.
*
* @return bool
*/
public function byId($id)
{
return $this->onceUsingId($id);
}
/**
* Add any custom claims.
*
* @return $this
*/
public function claims(array $claims)
{
$this->jwt->claims($claims);
return $this;
}
/**
* Get the raw Payload instance.
*
* @return Payload
*/
public function getPayload()
{
return $this->requireToken()->getPayload();
}
/**
* Alias for getPayload().
*
* @return Payload
*/
public function payload()
{
return $this->getPayload();
}
/**
* Set the token.
*
* @param Token|string $token
*
* @return $this
*/
public function setToken($token)
{
$this->jwt->setToken($token);
return $this;
}
/**
* Get the token ttl.
*
* @return int|null
*/
public function getTTL()
{
return $this->jwt->factory()->getTTL();
}
/**
* Set the token ttl.
*
* @param int|null $ttl
*
* @return $this
*/
public function setTTL($ttl)
{
$this->jwt->factory()->setTTL($ttl);
return $this;
}
/**
* Get the user provider used by the guard.
*
* @return UserProvider
*/
public function getProvider()
{
return $this->provider;
}
/**
* Set the user provider used by the guard.
*
* @return $this
*/
public function setProvider(UserProvider $provider)
{
$this->provider = $provider;
return $this;
}
/**
* Return the currently cached user.
*
* @return Authenticatable|null
*/
public function getUser()
{
return $this->user;
}
/**
* Set the current user.
*
* @return $this
*/
public function setUser(Authenticatable $user)
{
$result = $this->guardHelperSetUser($user);
$this->fireAuthenticatedEvent($user);
return $result;
}
/**
* Get the current request instance.
*
* @return Request
*/
public function getRequest()
{
return $this->request ?: Request::createFromGlobals();
}
/**
* Set the current request instance.
*
* @return $this
*/
public function setRequest(Request $request)
{
$this->request = $request;
return $this;
}
/**
* Get the last user we attempted to authenticate.
*
* @return Authenticatable
*/
public function getLastAttempted()
{
return $this->lastAttempted;
}
/**
* Determine if the user matches the credentials.
*
* @param array $credentials
*
* @return bool
*/
protected function hasValidCredentials($user, $credentials)
{
$validated = null !== $user && $this->provider->validateCredentials($user, $credentials);
if ($validated) {
$this->fireValidatedEvent($user);
}
return $validated;
}
/**
* Ensure the JWTSubject matches what is in the token.
*
* @return bool
*/
protected function validateSubject()
{
// If the provider doesn't have the necessary method
// to get the underlying model name then allow.
if (!method_exists($this->provider, 'getModel')) {
return true;
}
return $this->jwt->checkSubjectModel($this->provider->getModel());
}
/**
* Ensure that a token is available in the request.
*
* @return JWT
*
* @throws JWTException
*/
protected function requireToken()
{
if (!$this->jwt->setRequest($this->getRequest())->getToken()) {
throw new JWTException('Token could not be parsed from the request.');
}
return $this->jwt;
}
/**
* Fire the attempt event.
*
* @return void
*/
protected function fireAttemptEvent(array $credentials)
{
$this->events->dispatch(new Attempting(
$this->name,
$credentials,
false
));
}
/**
* Fires the validated event.
*
* @param Authenticatable $user
*
* @return void
*/
protected function fireValidatedEvent($user)
{
if (class_exists('Illuminate\Auth\Events\Validated')) {
$this->events->dispatch(
new \Illuminate\Auth\Events\Validated(
$this->name,
$user
)
);
}
}
/**
* Fire the failed authentication attempt event.
*
* @param Authenticatable|null $user
*
* @return void
*/
protected function fireFailedEvent($user, array $credentials)
{
$this->events->dispatch(new Failed(
$this->name,
$user,
$credentials
));
}
/**
* Fire the authenticated event.
*
* @param Authenticatable $user
*
* @return void
*/
protected function fireAuthenticatedEvent($user)
{
$this->events->dispatch(new Authenticated(
$this->name,
$user
));
}
/**
* Fire the login event.
*
* @param Authenticatable $user
* @param bool $remember
*
* @return void
*/
protected function fireLoginEvent($user, $remember = false)
{
$this->events->dispatch(new Login(
$this->name,
$user,
$remember
));
}
/**
* Fire the logout event.
*
* @param Authenticatable $user
* @param bool $remember
*
* @return void
*/
protected function fireLogoutEvent($user, $remember = false)
{
$this->events->dispatch(new Logout(
$this->name,
$user
));
}
/**
* Magically call the JWT instance.
*
* @param string $method
* @param array $parameters
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
if (method_exists($this->jwt, $method)) {
return call_user_func_array([$this->jwt, $method], $parameters);
}
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
throw new \BadMethodCallException("Method [$method] does not exist.");
}
}