-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathJWTTools.php
181 lines (152 loc) · 4.28 KB
/
JWTTools.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
<?php
declare(strict_types=1);
namespace AstrotechLabs\JWTTools;
use DateInterval;
use DateTime;
use Exception;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use InvalidArgumentException;
use stdClass;
use yii\db\ActiveRecord;
use yii\helpers\BaseStringHelper;
use yii\web\UnauthorizedHttpException;
final class JWTTools
{
private ActiveRecord $model;
private string $algorithm = 'HS256';
private string $secretKey;
private int $expiration;
private JWTPayload $payload;
private function __construct(string $secretKey, array $options = [])
{
$this->secretKey = $secretKey;
if (isset($options['algorithm'])) {
$this->algorithm = $options['algorithm'];
}
if (isset($options['expiration'])) {
$this->expiration = (int)$options['expiration'];
$options['exp'] = (new DateTime())
->add(new DateInterval("PT{$this->expiration}S"))
->getTimestamp();
}
$this->payload = JWTPayload::build($options);
}
/**
* @return string
*/
public function getAlgorithm(): string
{
return $this->algorithm;
}
/**
* @return string
*/
public function getSecretKey(): string
{
return $this->secretKey;
}
/**
* @return int
*/
public function getExpiration(): int
{
return $this->expiration;
}
/**
* @return JWTPayload
*/
public function getPayload(): JWTPayload
{
return $this->payload;
}
/**
* @param string $secretKey
* @param array $options
* @return JWTTools
*/
public static function build(string $secretKey, array $options = []): self
{
return new self($secretKey, $options);
}
/**
* @param ActiveRecord $model
* @param array $attributes
* @return $this
* @throws InvalidArgumentException
*/
public function withModel(ActiveRecord $model, array $attributes = []): self
{
$this->model = $model;
$this->payload->setSub($this->model->getPrimaryKey());
if (empty($attributes)) {
return $this;
}
foreach ($attributes as $attr) {
if (!$this->model->hasAttribute($attr)) {
throw new InvalidArgumentException(
"Attribute '{$attr}' doesn't exists in model class '" . get_class($this->model) . "' ."
);
}
$this->payload->addExtraAttribute($attr, $this->model->getAttribute($attr));
}
return $this;
}
public function withData($data = []): self
{
foreach($data as $k => $v){
$this->payload->addExtraAttribute($k, $v);
}
return $this;
}
public function getJWT(): string
{
try {
return JWT::encode(
$this->payload->getData(),
$this->secretKey,
$this->algorithm,
$this->payload->get('sub')
);
} catch (ExpiredException $e) {
throw new UnauthorizedHttpException('Authentication token is expired.');
}
}
public function decodeToken(string $token): stdClass
{
try {
return JWT::decode($token, $this->secretKey, [$this->algorithm]);
} catch (\Throwable $e) {
throw new UnauthorizedHttpException($e->getMessage());
}
}
/**
* @param string $token
* @return bool
*/
public function signatureIsValid(string $token): bool
{
list($header, $payload, $signatureProvided) = explode(".", $token);
$signature = hash_hmac('sha256', "{$header}.{$payload}", $this->secretKey, true);
$signature = str_replace("=", "", BaseStringHelper::base64UrlEncode($signature));
if ($signatureProvided !== $signature) {
return false;
}
return true;
}
/**
* @param string $token
* @return bool
* @throws Exception
*/
public function tokenIsExpired(string $token): bool
{
$decodedToken = $this->decodeToken($token);
$now = new DateTime();
$expiration = new DateTime("@{$decodedToken->exp}");
if ($now > $expiration) {
return true;
}
return false;
}
}