-
Notifications
You must be signed in to change notification settings - Fork 0
/
Administration.php
599 lines (535 loc) · 18.9 KB
/
Administration.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
<?php
namespace Horizom\Auth;
use Delight\Db\PdoDatabase;
use Delight\Db\PdoDsn;
use Delight\Db\Throwable\Error;
use Horizom\Auth\Error\DatabaseError;
use Horizom\Auth\Exception\UnknownIdException;
use Horizom\Auth\Exception\AmbiguousUsernameException;
use Horizom\Auth\Exception\InvalidPasswordException;
use Horizom\Auth\Exception\UnknownUsernameException;
use Horizom\Auth\Exception\InvalidEmailException;
use Horizom\Auth\Exception\EmailNotVerifiedException;
use Horizom\Auth\Exception\UserAlreadyExistsException;
use Horizom\Auth\Exception\DuplicateUsernameException;
/** Component that can be used for administrative tasks by privileged and authorized users */
class Administration extends AuthManager
{
/**
* @param PdoDatabase|PdoDsn|\PDO $databaseConnection the database connection to operate on
* @param string|null $dbTablePrefix (optional) the prefix for the names of all database tables used by this component
* @param string|null $dbSchema (optional) the schema name for all database tables used by this component
*/
public function __construct($databaseConnection, array $tables = null, $dbTablePrefix = null, $dbSchema = null)
{
parent::__construct($databaseConnection, $tables, $dbTablePrefix, $dbSchema);
if ($tables !== null) {
self::$tables = $tables;
}
}
/**
* Creates a new user
*
* @param string $email the email address to register
* @param string $password the password for the new account
* @param string|null $username (optional) the username that will be displayed
* @return int the ID of the user that has been created (if any)
* @throws InvalidEmailException if the email address was invalid
* @throws InvalidPasswordException if the password was invalid
* @throws UserAlreadyExistsException if a user with the specified email address already exists
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function createUser($email, $password, $username = null)
{
return $this->createUserInternal(false, $email, $password, $username, null);
}
/**
* Creates a new user while ensuring that the username is unique
*
* @param string $email the email address to register
* @param string $password the password for the new account
* @param string|null $username (optional) the username that will be displayed
* @return int the ID of the user that has been created (if any)
* @throws InvalidEmailException if the email address was invalid
* @throws InvalidPasswordException if the password was invalid
* @throws UserAlreadyExistsException if a user with the specified email address already exists
* @throws DuplicateUsernameException if the specified username wasn't unique
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function createUserWithUniqueUsername($email, $password, $username = null)
{
return $this->createUserInternal(true, $email, $password, $username, null);
}
/**
* Deletes the user with the specified ID
*
* This action cannot be undone
*
* @param int $id the ID of the user to delete
* @throws UnknownIdException if no user with the specified ID has been found
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function deleteUserById($id)
{
$numberOfDeletedUsers = $this->deleteUsersByColumnValue('id', (int) $id);
if ($numberOfDeletedUsers === 0) {
throw new UnknownIdException();
}
}
/**
* Deletes the user with the specified email address
*
* This action cannot be undone
*
* @param string $email the email address of the user to delete
* @throws InvalidEmailException if no user with the specified email address has been found
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function deleteUserByEmail($email)
{
$email = self::validateEmailAddress($email);
$numberOfDeletedUsers = $this->deleteUsersByColumnValue('email', $email);
if ($numberOfDeletedUsers === 0) {
throw new InvalidEmailException();
}
}
/**
* Deletes the user with the specified username
*
* This action cannot be undone
*
* @param string $username the username of the user to delete
* @throws UnknownUsernameException if no user with the specified username has been found
* @throws AmbiguousUsernameException if multiple users with the specified username have been found
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function deleteUserByUsername($username)
{
$userData = $this->getUserDataByUsername(
\trim($username),
['id']
);
$this->deleteUsersByColumnValue('id', (int) $userData['id']);
}
/**
* Assigns the specified role to the user with the given ID
*
* A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles)
*
* @param int $userId the ID of the user to assign the role to
* @param int $role the role as one of the constants from the {@see Role} class
* @throws UnknownIdException if no user with the specified ID has been found
*
* @see Role
*/
public function addRoleForUserById($userId, $role)
{
$userFound = $this->addRoleForUserByColumnValue(
'id',
(int) $userId,
$role
);
if ($userFound === false) {
throw new UnknownIdException();
}
}
/**
* Assigns the specified role to the user with the given email address
*
* A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles)
*
* @param string $userEmail the email address of the user to assign the role to
* @param int $role the role as one of the constants from the {@see Role} class
* @throws InvalidEmailException if no user with the specified email address has been found
*
* @see Role
*/
public function addRoleForUserByEmail($userEmail, $role)
{
$userEmail = self::validateEmailAddress($userEmail);
$userFound = $this->addRoleForUserByColumnValue(
'email',
$userEmail,
$role
);
if ($userFound === false) {
throw new InvalidEmailException();
}
}
/**
* Assigns the specified role to the user with the given username
*
* A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles)
*
* @param string $username the username of the user to assign the role to
* @param int $role the role as one of the constants from the {@see Role} class
* @throws UnknownUsernameException if no user with the specified username has been found
* @throws AmbiguousUsernameException if multiple users with the specified username have been found
*
* @see Role
*/
public function addRoleForUserByUsername($username, $role)
{
$userData = $this->getUserDataByUsername(
\trim($username),
['id']
);
$this->addRoleForUserByColumnValue(
'id',
(int) $userData['id'],
$role
);
}
/**
* Takes away the specified role from the user with the given ID
*
* A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles)
*
* @param int $userId the ID of the user to take the role away from
* @param int $role the role as one of the constants from the {@see Role} class
* @throws UnknownIdException if no user with the specified ID has been found
*
* @see Role
*/
public function removeRoleForUserById($userId, $role)
{
$userFound = $this->removeRoleForUserByColumnValue(
'id',
(int) $userId,
$role
);
if ($userFound === false) {
throw new UnknownIdException();
}
}
/**
* Takes away the specified role from the user with the given email address
*
* A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles)
*
* @param string $userEmail the email address of the user to take the role away from
* @param int $role the role as one of the constants from the {@see Role} class
* @throws InvalidEmailException if no user with the specified email address has been found
*
* @see Role
*/
public function removeRoleForUserByEmail($userEmail, $role)
{
$userEmail = self::validateEmailAddress($userEmail);
$userFound = $this->removeRoleForUserByColumnValue(
'email',
$userEmail,
$role
);
if ($userFound === false) {
throw new InvalidEmailException();
}
}
/**
* Takes away the specified role from the user with the given username
*
* A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles)
*
* @param string $username the username of the user to take the role away from
* @param int $role the role as one of the constants from the {@see Role} class
* @throws UnknownUsernameException if no user with the specified username has been found
* @throws AmbiguousUsernameException if multiple users with the specified username have been found
*
* @see Role
*/
public function removeRoleForUserByUsername($username, $role)
{
$userData = $this->getUserDataByUsername(
\trim($username),
['id']
);
$this->removeRoleForUserByColumnValue(
'id',
(int) $userData['id'],
$role
);
}
/**
* Returns whether the user with the given ID has the specified role
*
* @param int $userId the ID of the user to check the roles for
* @param int $role the role as one of the constants from the {@see Role} class
* @return bool
* @throws UnknownIdException if no user with the specified ID has been found
*
* @see Role
*/
public function doesUserHaveRole($userId, $role)
{
if (empty($role) || !\is_numeric($role)) {
return false;
}
$userId = (int) $userId;
$rolesBitmask = $this->db->selectValue(
'SELECT roles_mask FROM ' . $this->makeTableName('users') . ' WHERE id = ?',
[$userId]
);
if ($rolesBitmask === null) {
throw new UnknownIdException();
}
$role = (int) $role;
return ($rolesBitmask & $role) === $role;
}
/**
* Returns the roles of the user with the given ID, mapping the numerical values to their descriptive names
*
* @param int $userId the ID of the user to return the roles for
* @return array
* @throws UnknownIdException if no user with the specified ID has been found
*
* @see Role
*/
public function getRolesForUserById($userId)
{
$userId = (int) $userId;
$rolesBitmask = $this->db->selectValue(
'SELECT roles_mask FROM ' . $this->makeTableName('users') . ' WHERE id = ?',
[$userId]
);
if ($rolesBitmask === null) {
throw new UnknownIdException();
}
return \array_filter(
Role::getMap(),
function ($each) use ($rolesBitmask) {
return ($rolesBitmask & $each) === $each;
},
\ARRAY_FILTER_USE_KEY
);
}
/**
* Signs in as the user with the specified ID
*
* @param int $id the ID of the user to sign in as
* @throws UnknownIdException if no user with the specified ID has been found
* @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function logInAsUserById($id)
{
$numberOfMatchedUsers = $this->logInAsUserByColumnValue('id', (int) $id);
if ($numberOfMatchedUsers === 0) {
throw new UnknownIdException();
}
}
/**
* Signs in as the user with the specified email address
*
* @param string $email the email address of the user to sign in as
* @throws InvalidEmailException if no user with the specified email address has been found
* @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function logInAsUserByEmail($email)
{
$email = self::validateEmailAddress($email);
$numberOfMatchedUsers = $this->logInAsUserByColumnValue('email', $email);
if ($numberOfMatchedUsers === 0) {
throw new InvalidEmailException();
}
}
/**
* Signs in as the user with the specified display name
*
* @param string $username the display name of the user to sign in as
* @throws UnknownUsernameException if no user with the specified username has been found
* @throws AmbiguousUsernameException if multiple users with the specified username have been found
* @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function logInAsUserByUsername($username)
{
$numberOfMatchedUsers = $this->logInAsUserByColumnValue('username', \trim($username));
if ($numberOfMatchedUsers === 0) {
throw new UnknownUsernameException();
} elseif ($numberOfMatchedUsers > 1) {
throw new AmbiguousUsernameException();
}
}
/**
* Changes the password for the user with the given ID
*
* @param int $userId the ID of the user whose password to change
* @param string $newPassword the new password to set
* @throws UnknownIdException if no user with the specified ID has been found
* @throws InvalidPasswordException if the desired new password has been invalid
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function changePasswordForUserById($userId, $newPassword)
{
$userId = (int) $userId;
$newPassword = self::validatePassword($newPassword);
$this->updatePasswordInternal(
$userId,
$newPassword
);
$this->forceLogoutForUserById($userId);
}
/**
* Changes the password for the user with the given username
*
* @param string $username the username of the user whose password to change
* @param string $newPassword the new password to set
* @throws UnknownUsernameException if no user with the specified username has been found
* @throws AmbiguousUsernameException if multiple users with the specified username have been found
* @throws InvalidPasswordException if the desired new password has been invalid
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function changePasswordForUserByUsername($username, $newPassword)
{
$userData = $this->getUserDataByUsername(
\trim($username),
['id']
);
$this->changePasswordForUserById(
(int) $userData['id'],
$newPassword
);
}
/**
* Deletes all existing users where the column with the specified name has the given value
*
* You must never pass untrusted input to the parameter that takes the column name
*
* @param string $columnName the name of the column to filter by
* @param mixed $columnValue the value to look for in the selected column
* @return int the number of deleted users
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function deleteUsersByColumnValue($columnName, $columnValue)
{
try {
return $this->db->delete(
$this->makeTableNameComponents('users'),
[
$columnName => $columnValue
]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
}
/**
* Modifies the roles for the user where the column with the specified name has the given value
*
* You must never pass untrusted input to the parameter that takes the column name
*
* @param string $columnName the name of the column to filter by
* @param mixed $columnValue the value to look for in the selected column
* @param callable $modification the modification to apply to the existing bitmask of roles
* @return bool whether any user with the given column constraints has been found
* @throws AuthError if an internal problem occurred (do *not* catch)
*
* @see Role
*/
private function modifyRolesForUserByColumnValue($columnName, $columnValue, callable $modification)
{
try {
$userData = $this->db->selectRow(
'SELECT id, roles_mask FROM ' . $this->makeTableName('users') . ' WHERE ' . $columnName . ' = ?',
[$columnValue]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
if ($userData === null) {
return false;
}
$newRolesBitmask = $modification($userData['roles_mask']);
try {
$this->db->exec(
'UPDATE ' . $this->makeTableName('users') . ' SET roles_mask = ? WHERE id = ?',
[
$newRolesBitmask,
(int) $userData['id']
]
);
return true;
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
}
/**
* Assigns the specified role to the user where the column with the specified name has the given value
*
* You must never pass untrusted input to the parameter that takes the column name
*
* @param string $columnName the name of the column to filter by
* @param mixed $columnValue the value to look for in the selected column
* @param int $role the role as one of the constants from the {@see Role} class
* @return bool whether any user with the given column constraints has been found
*
* @see Role
*/
private function addRoleForUserByColumnValue($columnName, $columnValue, $role)
{
$role = (int) $role;
return $this->modifyRolesForUserByColumnValue(
$columnName,
$columnValue,
function ($oldRolesBitmask) use ($role) {
return $oldRolesBitmask | $role;
}
);
}
/**
* Takes away the specified role from the user where the column with the specified name has the given value
*
* You must never pass untrusted input to the parameter that takes the column name
*
* @param string $columnName the name of the column to filter by
* @param mixed $columnValue the value to look for in the selected column
* @param int $role the role as one of the constants from the {@see Role} class
* @return bool whether any user with the given column constraints has been found
*
* @see Role
*/
private function removeRoleForUserByColumnValue($columnName, $columnValue, $role)
{
$role = (int) $role;
return $this->modifyRolesForUserByColumnValue(
$columnName,
$columnValue,
function ($oldRolesBitmask) use ($role) {
return $oldRolesBitmask & ~$role;
}
);
}
/**
* Signs in as the user for which the column with the specified name has the given value
*
* You must never pass untrusted input to the parameter that takes the column name
*
* @param string $columnName the name of the column to filter by
* @param mixed $columnValue the value to look for in the selected column
* @return int the number of matched users (where only a value of one means that the login may have been successful)
* @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function logInAsUserByColumnValue($columnName, $columnValue)
{
try {
$users = $this->db->select(
'SELECT verified, id, email, username, status, roles_mask FROM ' . $this->makeTableName('users') . ' WHERE ' . $columnName . ' = ? LIMIT 2 OFFSET 0',
[$columnValue]
);
} catch (Error $e) {
throw new DatabaseError($e->getMessage());
}
$numberOfMatchingUsers = ($users !== null) ? \count($users) : 0;
if ($numberOfMatchingUsers === 1) {
$user = $users[0];
if ((int) $user['verified'] === 1) {
$this->onLoginSuccessful($user['id'], $user['email'], $user['username'], $user['status'], $user['roles_mask'], \PHP_INT_MAX, false);
} else {
throw new EmailNotVerifiedException();
}
}
return $numberOfMatchingUsers;
}
}