-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathToken.php
79 lines (69 loc) · 2.28 KB
/
Token.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
<?php
namespace Yggdrasil\Models;
use Cache;
use Lcobucci\JWT;
use Ramsey\Uuid\Uuid;
class Token
{
public $owner;
public $profileId = '';
public $createdAt;
public $clientToken;
public $accessToken;
public function __construct($clientToken = '', $accessToken = '')
{
$this->clientToken = $clientToken;
$this->accessToken = $accessToken;
$this->createdAt = time();
}
public function isValid()
{
if (str_contains($this->accessToken, '.')) {
$jwtConfig = JWT\Configuration::forSymmetricSigner(
new JWT\Signer\Hmac\Sha256(),
JWT\Signer\Key\InMemory::plainText(config('jwt.secret', ''))
);
$jwtConfig->setValidationConstraints(
new JWT\Validation\Constraint\IssuedBy('Yggdrasil-Auth'),
new JWT\Validation\Constraint\RelatedTo(
Uuid::uuid5(Uuid::NAMESPACE_DNS, $this->owner)->getHex()->toString()
)
);
$token = $jwtConfig->parser()->parse($this->accessToken);
return $jwtConfig->validator()->validate($token, ...$jwtConfig->validationConstraints());
} else {
// fallback for legacy UUID-format accessToken
return (time() - $this->createdAt - option('ygg_token_expire_1')) < 0;
}
}
public function isRefreshable()
{
return (time() - $this->createdAt - option('ygg_token_expire_2')) < 0;
}
// 这个方法只是为了方便写日志
public function serialize()
{
return [
'clientToken' => $this->clientToken,
'accessToken' => $this->accessToken,
'owner' => $this->owner,
'createdAt' => $this->createdAt,
];
}
/**
* Search the specified token, or null if the token does not exist or has expired.
* The returned token is guaranteed to be refreshable, but it may not be valid.
*/
public static function find(string $accessToken)
{
$token = Cache::get("yggdrasil-token-$accessToken");
if ($token) {
if ($token->isRefreshable()) {
return $token;
} else {
Cache::forget("yggdrasil-token-$accessToken");
}
}
return null;
}
}