1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Platine Framework |
5
|
|
|
* |
6
|
|
|
* Platine Framework is a lightweight, high-performance, simple and elegant |
7
|
|
|
* PHP Web framework |
8
|
|
|
* |
9
|
|
|
* This content is released under the MIT License (MIT) |
10
|
|
|
* |
11
|
|
|
* Copyright (c) 2020 Platine Framework |
12
|
|
|
* |
13
|
|
|
* Permission is hereby granted, free of charge, to any person obtaining a copy |
14
|
|
|
* of this software and associated documentation files (the "Software"), to deal |
15
|
|
|
* in the Software without restriction, including without limitation the rights |
16
|
|
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
17
|
|
|
* copies of the Software, and to permit persons to whom the Software is |
18
|
|
|
* furnished to do so, subject to the following conditions: |
19
|
|
|
* |
20
|
|
|
* The above copyright notice and this permission notice shall be included in all |
21
|
|
|
* copies or substantial portions of the Software. |
22
|
|
|
* |
23
|
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
24
|
|
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
25
|
|
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
26
|
|
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
27
|
|
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
28
|
|
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
29
|
|
|
* SOFTWARE. |
30
|
|
|
*/ |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @file JWTAuthentication.php |
34
|
|
|
* |
35
|
|
|
* The Authentication using JWT class |
36
|
|
|
* |
37
|
|
|
* @package Platine\Framework\Auth\Authentication |
38
|
|
|
* @author Platine Developers team |
39
|
|
|
* @copyright Copyright (c) 2020 |
40
|
|
|
* @license http://opensource.org/licenses/MIT MIT License |
41
|
|
|
* @link https://www.platine-php.com |
42
|
|
|
* @version 1.0.0 |
43
|
|
|
* @filesource |
44
|
|
|
*/ |
45
|
|
|
|
46
|
|
|
declare(strict_types=1); |
47
|
|
|
|
48
|
|
|
namespace Platine\Framework\Auth\Authentication; |
49
|
|
|
|
50
|
|
|
use DateTime; |
51
|
|
|
use Platine\Config\Config; |
52
|
|
|
use Platine\Framework\Auth\AuthenticationInterface; |
53
|
|
|
use Platine\Framework\Auth\Entity\Token; |
54
|
|
|
use Platine\Framework\Auth\Entity\User; |
55
|
|
|
use Platine\Framework\Auth\Enum\UserStatus; |
56
|
|
|
use Platine\Framework\Auth\Exception\AccountLockedException; |
57
|
|
|
use Platine\Framework\Auth\Exception\AccountNotFoundException; |
58
|
|
|
use Platine\Framework\Auth\Exception\InvalidCredentialsException; |
59
|
|
|
use Platine\Framework\Auth\Exception\MissingCredentialsException; |
60
|
|
|
use Platine\Framework\Auth\IdentityInterface; |
61
|
|
|
use Platine\Framework\Auth\Repository\TokenRepository; |
62
|
|
|
use Platine\Framework\Auth\Repository\UserRepository; |
63
|
|
|
use Platine\Framework\Security\JWT\Exception\JWTException; |
64
|
|
|
use Platine\Framework\Security\JWT\JWT; |
65
|
|
|
use Platine\Http\ServerRequestInterface; |
66
|
|
|
use Platine\Logger\LoggerInterface; |
67
|
|
|
use Platine\Security\Hash\HashInterface; |
68
|
|
|
use Platine\Stdlib\Helper\Str; |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @class JWTAuthentication |
72
|
|
|
* @package Platine\Framework\Auth\Authentication |
73
|
|
|
* @template T |
74
|
|
|
*/ |
75
|
|
|
class JWTAuthentication implements AuthenticationInterface |
76
|
|
|
{ |
77
|
|
|
/** |
78
|
|
|
* Create new instance |
79
|
|
|
* @param JWT $jwt |
80
|
|
|
* @param LoggerInterface $logger |
81
|
|
|
* @param Config<T> $config |
82
|
|
|
* @param HashInterface $hash |
83
|
|
|
* @param UserRepository $userRepository |
84
|
|
|
* @param TokenRepository $tokenRepository |
85
|
|
|
* @param ServerRequestInterface $request |
86
|
|
|
*/ |
87
|
|
|
public function __construct( |
88
|
|
|
protected JWT $jwt, |
89
|
|
|
protected LoggerInterface $logger, |
90
|
|
|
protected Config $config, |
91
|
|
|
protected HashInterface $hash, |
92
|
|
|
protected UserRepository $userRepository, |
93
|
|
|
protected TokenRepository $tokenRepository, |
94
|
|
|
protected ServerRequestInterface $request |
95
|
|
|
) { |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
/** |
99
|
|
|
* {@inheritdoc} |
100
|
|
|
*/ |
101
|
|
|
public function getUser(): IdentityInterface |
102
|
|
|
{ |
103
|
|
|
if ($this->isLogged() === false) { |
104
|
|
|
throw new AccountNotFoundException('User not logged', 401); |
105
|
|
|
} |
106
|
|
|
|
107
|
|
|
$payload = $this->jwt->getPayload(); |
108
|
|
|
$id = (int) ($payload['sub'] ?? -1); |
109
|
|
|
|
110
|
|
|
$user = $this->userRepository->find($id); |
111
|
|
|
if ($user === null) { |
112
|
|
|
throw new AccountNotFoundException( |
113
|
|
|
'Can not find the logged user information, may be data is corrupted', |
114
|
|
|
401 |
115
|
|
|
); |
116
|
|
|
} |
117
|
|
|
|
118
|
|
|
return $user; |
|
|
|
|
119
|
|
|
} |
120
|
|
|
|
121
|
|
|
/** |
122
|
|
|
* {@inheritdoc} |
123
|
|
|
*/ |
124
|
|
|
public function getId(): int|string |
125
|
|
|
{ |
126
|
|
|
if ($this->isLogged() === false) { |
127
|
|
|
throw new AccountNotFoundException('User not logged', 401); |
128
|
|
|
} |
129
|
|
|
|
130
|
|
|
$payload = $this->jwt->getPayload(); |
131
|
|
|
$id = (int) ($payload['sub'] ?? -1); |
132
|
|
|
|
133
|
|
|
return $id; |
134
|
|
|
} |
135
|
|
|
|
136
|
|
|
/** |
137
|
|
|
* {@inheritdoc} |
138
|
|
|
*/ |
139
|
|
|
public function isLogged(): bool |
140
|
|
|
{ |
141
|
|
|
$request = $this->request; |
142
|
|
|
$headerName = $this->config->get('api.auth.headers.name', 'Authorization'); |
143
|
|
|
$tokenHeader = $request->getHeaderLine($headerName); |
144
|
|
|
if (empty($tokenHeader)) { |
145
|
|
|
$this->logger->error('API authentication failed missing token header'); |
146
|
|
|
|
147
|
|
|
return false; |
148
|
|
|
} |
149
|
|
|
$tokenType = $this->config->get('api.auth.headers.token_type', 'Bearer'); |
150
|
|
|
$secret = $this->config->get('api.sign.secret', ''); |
151
|
|
|
|
152
|
|
|
$token = Str::replaceFirst($tokenType . ' ', '', $tokenHeader); |
153
|
|
|
|
154
|
|
|
$this->jwt->setSecret($secret); |
155
|
|
|
try { |
156
|
|
|
$this->jwt->decode($token); |
157
|
|
|
|
158
|
|
|
return true; |
159
|
|
|
} catch (JWTException $ex) { |
160
|
|
|
$this->logger->error('API authentication failed: {message}', [ |
161
|
|
|
'message' => $ex->getMessage(), |
162
|
|
|
]); |
163
|
|
|
} |
164
|
|
|
|
165
|
|
|
return false; |
166
|
|
|
} |
167
|
|
|
|
168
|
|
|
/** |
169
|
|
|
* {@inheritdoc} |
170
|
|
|
*/ |
171
|
|
|
public function login( |
172
|
|
|
array $credentials = [], |
173
|
|
|
bool $remeberMe = false, |
174
|
|
|
bool $withPassword = true |
175
|
|
|
): array { |
176
|
|
|
if (!isset($credentials['username'])) { |
177
|
|
|
throw new MissingCredentialsException( |
178
|
|
|
'Missing username information', |
179
|
|
|
401 |
180
|
|
|
); |
181
|
|
|
} |
182
|
|
|
|
183
|
|
|
if ($withPassword && !isset($credentials['password'])) { |
184
|
|
|
throw new MissingCredentialsException( |
185
|
|
|
'Missing password information', |
186
|
|
|
401 |
187
|
|
|
); |
188
|
|
|
} |
189
|
|
|
|
190
|
|
|
$username = $credentials['username']; |
191
|
|
|
$password = $credentials['password'] ?? ''; |
192
|
|
|
$user = $this->getUserEntity($username, $password, $withPassword); |
193
|
|
|
|
194
|
|
|
if ($user === null) { |
195
|
|
|
throw new AccountNotFoundException( |
196
|
|
|
sprintf( |
197
|
|
|
'Can not find the user [%s]', |
198
|
|
|
$username |
199
|
|
|
), |
200
|
|
|
401 |
201
|
|
|
); |
202
|
|
|
} elseif ($user->status === UserStatus::LOCKED) { |
|
|
|
|
203
|
|
|
throw new AccountLockedException( |
204
|
|
|
sprintf('User [%s] is locked', $username), |
205
|
|
|
401 |
206
|
|
|
); |
207
|
|
|
} |
208
|
|
|
|
209
|
|
|
if ($withPassword && $this->hash->verify($password, $user->password) === false) { |
|
|
|
|
210
|
|
|
throw new InvalidCredentialsException( |
211
|
|
|
sprintf('Invalid credentials for user [%s]', $username), |
212
|
|
|
401 |
213
|
|
|
); |
214
|
|
|
} |
215
|
|
|
|
216
|
|
|
$permissions = []; |
217
|
|
|
$roles = $user->roles; |
|
|
|
|
218
|
|
|
foreach ($roles as $role) { |
219
|
|
|
$rolePermissions = $role->permissions; |
220
|
|
|
foreach ($rolePermissions as $permission) { |
221
|
|
|
if (in_array($permission->code, $permissions) === false) { |
222
|
|
|
$permissions[] = $permission->code; |
223
|
|
|
} |
224
|
|
|
} |
225
|
|
|
} |
226
|
|
|
|
227
|
|
|
$secret = $this->config->get('api.sign.secret'); |
228
|
|
|
$expire = $this->config->get('api.auth.token_expire', 900); |
229
|
|
|
$refreshExpire = $this->config->get('api.auth.refresh_token_expire', 30 * 86400); |
230
|
|
|
$tokenExpire = time() + $expire; |
231
|
|
|
$refreshTokenExpire = time() + $refreshExpire; |
232
|
|
|
$this->jwt->setSecret($secret) |
233
|
|
|
->setPayload([ |
234
|
|
|
'sub' => $user->id, |
|
|
|
|
235
|
|
|
'exp' => $tokenExpire, |
236
|
|
|
'permissions' => $permissions, |
237
|
|
|
]) |
238
|
|
|
->sign(); |
239
|
|
|
|
240
|
|
|
$refreshToken = Str::random(64); |
241
|
|
|
$jwtToken = $this->jwt->getToken(); |
242
|
|
|
|
243
|
|
|
$token = $this->tokenRepository->create([ |
244
|
|
|
'token' => $jwtToken, |
245
|
|
|
'refresh_token' => $refreshToken, |
246
|
|
|
'expire_at' => (new DateTime())->setTimestamp($refreshTokenExpire), |
247
|
|
|
'user_id' => $user->id, |
248
|
|
|
]); |
249
|
|
|
$this->tokenRepository->save($token); |
250
|
|
|
|
251
|
|
|
$data = [ |
252
|
|
|
'user' => [ |
253
|
|
|
'id' => $user->id, |
254
|
|
|
'username' => $user->username, |
|
|
|
|
255
|
|
|
'lastname' => $user->lastname, |
|
|
|
|
256
|
|
|
'firstname' => $user->firstname, |
|
|
|
|
257
|
|
|
'email' => $user->email, |
|
|
|
|
258
|
|
|
'permissions' => $permissions, |
259
|
|
|
], |
260
|
|
|
'token' => $jwtToken, |
261
|
|
|
'refresh_token' => $refreshToken, |
262
|
|
|
]; |
263
|
|
|
|
264
|
|
|
return array_merge($data, $this->getUserData($user, $token)); |
265
|
|
|
} |
266
|
|
|
|
267
|
|
|
/** |
268
|
|
|
* {@inheritdoc} |
269
|
|
|
*/ |
270
|
|
|
public function logout(bool $destroy = true): void |
271
|
|
|
{ |
272
|
|
|
// do nothing now |
273
|
|
|
} |
274
|
|
|
|
275
|
|
|
/** |
276
|
|
|
* Return the user entity |
277
|
|
|
* @param string $username |
278
|
|
|
* @param string $password |
279
|
|
|
* @param bool $withPassword wether to use password to login |
280
|
|
|
* @return User|null |
281
|
|
|
*/ |
282
|
|
|
protected function getUserEntity( |
283
|
|
|
string $username, |
284
|
|
|
string $password, |
|
|
|
|
285
|
|
|
bool $withPassword = true |
|
|
|
|
286
|
|
|
): ?User { |
287
|
|
|
return $this->userRepository->with('roles.permissions') |
|
|
|
|
288
|
|
|
->findBy(['username' => $username]); |
289
|
|
|
} |
290
|
|
|
|
291
|
|
|
/** |
292
|
|
|
* Return the user additional data |
293
|
|
|
* @param User $user |
294
|
|
|
* @param Token $token |
295
|
|
|
* @return array<string, mixed> |
296
|
|
|
*/ |
297
|
|
|
protected function getUserData(User $user, Token $token): array |
|
|
|
|
298
|
|
|
{ |
299
|
|
|
return [ |
300
|
|
|
'refresh_token_expire' => $token->expire_at->getTimestamp() |
|
|
|
|
301
|
|
|
]; |
302
|
|
|
} |
303
|
|
|
} |
304
|
|
|
|