-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathUserIdentityModel.php
More file actions
601 lines (509 loc) · 16.2 KB
/
UserIdentityModel.php
File metadata and controls
601 lines (509 loc) · 16.2 KB
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
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Shield\Models;
use CodeIgniter\Database\RawSql;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\Authenticators\AccessTokens;
use CodeIgniter\Shield\Authentication\Authenticators\HmacSha256;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Authentication\HMAC\HmacEncrypter;
use CodeIgniter\Shield\Authentication\Passwords;
use CodeIgniter\Shield\Entities\AccessToken;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Shield\Entities\UserIdentity;
use CodeIgniter\Shield\Exceptions\LogicException;
use CodeIgniter\Shield\Exceptions\ValidationException;
use Exception;
use Faker\Generator;
use InvalidArgumentException;
use ReflectionException;
class UserIdentityModel extends BaseModel
{
protected $primaryKey = 'id';
protected $returnType = UserIdentity::class;
protected $useSoftDeletes = false;
protected $allowedFields = [
'user_id',
'type',
'name',
'secret',
'secret2',
'expires',
'extra',
'force_reset',
'last_used_at',
];
protected $useTimestamps = true;
protected function initialize(): void
{
parent::initialize();
$this->table = $this->tables['identities'];
}
/**
* Inserts a record
*
* @param array|object $data
*
* @throws DatabaseException
*/
public function create($data): void
{
$this->disableDBDebug();
$return = $this->insert($data);
$this->checkQueryReturn($return);
}
/**
* Creates a new identity for this user with an email/password
* combination.
*
* @phpstan-param array{email: string, password: string} $credentials
*/
public function createEmailIdentity(User $user, array $credentials): void
{
$this->checkUserId($user);
/** @var Passwords $passwords */
$passwords = service('passwords');
$return = $this->insert([
'user_id' => $user->id,
'type' => Session::ID_TYPE_EMAIL_PASSWORD,
'secret' => $credentials['email'],
'secret2' => $passwords->hash($credentials['password']),
]);
$this->checkQueryReturn($return);
}
private function checkUserId(User $user): void
{
if ($user->id === null) {
throw new LogicException(
'"$user->id" is null. You should not use the incomplete User object.',
);
}
}
/**
* Create an identity with 6 digits code for auth action
*
* @param array{type: string, name: string, extra: string} $data
* @param callable $codeGenerator generate secret code
*
* @return string secret
*/
public function createCodeIdentity(
User $user,
array $data,
callable $codeGenerator,
): string {
$this->checkUserId($user);
helper('text');
// Create an identity for the action
$maxTry = 5;
$data['user_id'] = $user->id;
while (true) {
$data['secret'] = $codeGenerator();
try {
$this->create($data);
break;
} catch (DatabaseException $e) {
$maxTry--;
if ($maxTry === 0) {
throw $e;
}
}
}
return $data['secret'];
}
/**
* Generates a new personal access token for the user.
*
* @param string $name Token name
* @param list<string> $scopes Permissions the token grants
* @param Time $expiresAt Expiration date
*
* @throws InvalidArgumentException
*/
public function generateAccessToken(User $user, string $name, array $scopes = ['*'], ?Time $expiresAt = null): AccessToken
{
$this->checkUserId($user);
helper('text');
$return = $this->insert([
'type' => AccessTokens::ID_TYPE_ACCESS_TOKEN,
'user_id' => $user->id,
'name' => $name,
'secret' => hash('sha256', $rawToken = random_string('crypto', 64)),
'expires' => $expiresAt,
'extra' => serialize($scopes),
]);
$this->checkQueryReturn($return);
/** @var AccessToken $token */
$token = $this
->asObject(AccessToken::class)
->find($this->getInsertID());
$token->raw_token = $rawToken;
return $token;
}
public function getAccessTokenByRawToken(string $rawToken): ?AccessToken
{
return $this
->where('type', AccessTokens::ID_TYPE_ACCESS_TOKEN)
->where('secret', hash('sha256', $rawToken))
->asObject(AccessToken::class)
->first();
}
public function getAccessToken(User $user, string $rawToken): ?AccessToken
{
$this->checkUserId($user);
return $this->where('user_id', $user->id)
->where('type', AccessTokens::ID_TYPE_ACCESS_TOKEN)
->where('secret', hash('sha256', $rawToken))
->asObject(AccessToken::class)
->first();
}
/**
* Given the ID, returns the given access token.
*
* @param int|string $id
*/
public function getAccessTokenById($id, User $user): ?AccessToken
{
$this->checkUserId($user);
return $this->where('user_id', $user->id)
->where('type', AccessTokens::ID_TYPE_ACCESS_TOKEN)
->where('id', $id)
->asObject(AccessToken::class)
->first();
}
/**
* @return list<AccessToken>
*/
public function getAllAccessTokens(User $user): array
{
$this->checkUserId($user);
return $this
->where('user_id', $user->id)
->where('type', AccessTokens::ID_TYPE_ACCESS_TOKEN)
->orderBy($this->primaryKey)
->asObject(AccessToken::class)
->findAll();
}
/**
* Updates or sets expiration date of users' AccessToken or HMAC Token by ID.
*
* @param Time $expiresAt Expiration date
* @param mixed $id
*
* @return bool Returns true if expiration date was set or updated.
*/
public function setIdentityExpirationById($id, User $user, ?Time $expiresAt = null): bool
{
$this->checkUserId($user);
return $this->where('user_id', $user->id)
->where('id', $id)
->set(['expires' => $expiresAt])
->update();
}
// HMAC
/**
* Find and Retrieve the HMAC AccessToken based on Token alone
*
* @return ?AccessToken Full HMAC Access Token object
*/
public function getHmacTokenByKey(string $key): ?AccessToken
{
return $this
->where('type', HmacSha256::ID_TYPE_HMAC_TOKEN)
->where('secret', $key)
->asObject(AccessToken::class)
->first();
}
/**
* Generates a new personal access token for the user.
*
* @param string $name Token name
* @param list<string> $scopes Permissions the token grants
* @param Time $expiresAt Expiration date
*
* @throws Exception
* @throws InvalidArgumentException
* @throws ReflectionException
*/
public function generateHmacToken(User $user, string $name, array $scopes = ['*'], ?Time $expiresAt = null): AccessToken
{
$this->checkUserId($user);
$encrypter = new HmacEncrypter();
$rawSecretKey = $encrypter->generateSecretKey();
$secretKey = $encrypter->encrypt($rawSecretKey);
$return = $this->insert([
'type' => HmacSha256::ID_TYPE_HMAC_TOKEN,
'user_id' => $user->id,
'name' => $name,
'secret' => bin2hex(random_bytes(16)), // Key
'secret2' => $secretKey,
'expires' => $expiresAt,
'extra' => serialize($scopes),
]);
$this->checkQueryReturn($return);
/** @var AccessToken $token */
$token = $this
->asObject(AccessToken::class)
->find($this->getInsertID());
$token->rawSecretKey = $rawSecretKey;
return $token;
}
/**
* Retrieve Token object for selected HMAC Token.
* Note: These tokens are not hashed as they are considered shared secrets.
*
* @param User $user User Object
* @param string $key HMAC Key String
*
* @return ?AccessToken Full HMAC Access Token
*/
public function getHmacToken(User $user, string $key): ?AccessToken
{
$this->checkUserId($user);
return $this->where('user_id', $user->id)
->where('type', HmacSha256::ID_TYPE_HMAC_TOKEN)
->where('secret', $key)
->asObject(AccessToken::class)
->first();
}
/**
* Given the ID, returns the given access token.
*
* @param int|string $id
* @param User $user User Object
*
* @return ?AccessToken Full HMAC Access Token
*/
public function getHmacTokenById($id, User $user): ?AccessToken
{
$this->checkUserId($user);
return $this->where('user_id', $user->id)
->where('type', HmacSha256::ID_TYPE_HMAC_TOKEN)
->where('id', $id)
->asObject(AccessToken::class)
->first();
}
/**
* Retrieve all HMAC tokes for users
*
* @param User $user User object
*
* @return list<AccessToken>
*/
public function getAllHmacTokens(User $user): array
{
$this->checkUserId($user);
return $this
->where('user_id', $user->id)
->where('type', HmacSha256::ID_TYPE_HMAC_TOKEN)
->orderBy($this->primaryKey)
->asObject(AccessToken::class)
->findAll();
}
/**
* Delete any HMAC tokens for the given key.
*
* @param User $user User object
* @param string $key HMAC Key
*/
public function revokeHmacToken(User $user, string $key): void
{
$this->checkUserId($user);
$return = $this->where('user_id', $user->id)
->where('type', HmacSha256::ID_TYPE_HMAC_TOKEN)
->where('secret', $key)
->delete();
$this->checkQueryReturn($return);
}
/**
* Revokes all access tokens for this user.
*/
public function revokeAllHmacTokens(User $user): void
{
$this->checkUserId($user);
$return = $this->where('user_id', $user->id)
->where('type', HmacSha256::ID_TYPE_HMAC_TOKEN)
->delete();
$this->checkQueryReturn($return);
}
/**
* Used by 'magic-link'.
*/
public function getIdentityBySecret(string $type, ?string $secret): ?UserIdentity
{
if ($secret === null) {
return null;
}
return $this->where('type', $type)
->where('secret', $secret)
->first();
}
/**
* Returns all identities.
*
* @return list<UserIdentity>
*/
public function getIdentities(User $user): array
{
$this->checkUserId($user);
return $this->where('user_id', $user->id)->orderBy($this->primaryKey)->findAll();
}
/**
* @param list<int>|list<string> $userIds
*
* @return list<UserIdentity>
*/
public function getIdentitiesByUserIds(array $userIds): array
{
return $this->whereIn('user_id', $userIds)->orderBy($this->primaryKey)->findAll();
}
/**
* Returns the first identity of the type.
*/
public function getIdentityByType(User $user, string $type): ?UserIdentity
{
$this->checkUserId($user);
return $this->where('user_id', $user->id)
->where('type', $type)
->orderBy($this->primaryKey)
->first();
}
/**
* Returns all identities for the specific types.
*
* @param list<string> $types
*
* @return list<UserIdentity>
*/
public function getIdentitiesByTypes(User $user, array $types): array
{
$this->checkUserId($user);
if ($types === []) {
return [];
}
return $this->where('user_id', $user->id)
->whereIn('type', $types)
->orderBy($this->primaryKey)
->findAll();
}
/**
* Update the last used at date for an identity record.
*/
public function touchIdentity(UserIdentity $identity): void
{
$identity->last_used_at = Time::now();
$return = $this->save($identity);
$this->checkQueryReturn($return);
}
public function deleteIdentitiesByType(User $user, string $type): void
{
$this->checkUserId($user);
$return = $this->where('user_id', $user->id)
->where('type', $type)
->delete();
$this->checkQueryReturn($return);
}
/**
* Delete any access tokens for the given raw token.
*/
public function revokeAccessToken(User $user, string $rawToken): void
{
$this->checkUserId($user);
$return = $this->where('user_id', $user->id)
->where('type', AccessTokens::ID_TYPE_ACCESS_TOKEN)
->where('secret', hash('sha256', $rawToken))
->delete();
$this->checkQueryReturn($return);
}
/**
* Delete any access tokens for the given secret token.
*/
public function revokeAccessTokenBySecret(User $user, string $secretToken): void
{
$this->checkUserId($user);
$return = $this->where('user_id', $user->id)
->where('type', AccessTokens::ID_TYPE_ACCESS_TOKEN)
->where('secret', $secretToken)
->delete();
$this->checkQueryReturn($return);
}
/**
* Revokes all access tokens for this user.
*/
public function revokeAllAccessTokens(User $user): void
{
$this->checkUserId($user);
$return = $this->where('user_id', $user->id)
->where('type', AccessTokens::ID_TYPE_ACCESS_TOKEN)
->delete();
$this->checkQueryReturn($return);
}
/**
* Force password reset for multiple users.
*
* @param list<int>|list<string> $userIds
*/
public function forceMultiplePasswordReset(array $userIds): void
{
$this->where(['type' => Session::ID_TYPE_EMAIL_PASSWORD, 'force_reset' => 0]);
$this->whereIn('user_id', $userIds);
$this->set('force_reset', 1);
$return = $this->update();
$this->checkQueryReturn($return);
}
/**
* Force global password reset.
* This is useful for enforcing a password reset
* for ALL users in case of a security breach.
*/
public function forceGlobalPasswordReset(): void
{
$whereFilter = [
'type' => Session::ID_TYPE_EMAIL_PASSWORD,
'force_reset' => 0,
];
$this->where($whereFilter);
$this->set('force_reset', 1);
$return = $this->update();
$this->checkQueryReturn($return);
}
/**
* Override the Model's `update()` method.
* Throws an Exception when it fails.
*
* @param int|list<int|string>|RawSql|string|null $id
* @param array|object|null $row
*
* @return true if the update is successful
*
* @throws ValidationException
*/
public function update($id = null, $row = null): bool
{
$result = parent::update($id, $row);
$this->checkQueryReturn($result);
return true;
}
public function fake(Generator &$faker): UserIdentity
{
return new UserIdentity([
'user_id' => fake(UserModel::class)->id,
'type' => Session::ID_TYPE_EMAIL_PASSWORD,
'name' => null,
'secret' => $faker->unique()->email(),
'secret2' => password_hash('secret', PASSWORD_DEFAULT),
'expires' => null,
'extra' => null,
'force_reset' => false,
'last_used_at' => null,
]);
}
}