-
Notifications
You must be signed in to change notification settings - Fork 0
/
Auth.php
103 lines (84 loc) · 2.75 KB
/
Auth.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
<?php
namespace Framework\Authentication;
use App\Models\Role;
use App\Models\User;
use App\Models\UserRole;
use Framework\Facades\Http;
class Auth
{
/** Caches the user role assignments the duration of one request */
private static array $roleCache = [];
/** Get the id of the logged in user */
public static function id(): ?int
{
return Session::getValue('userId');
}
/** Check if the user is logged in */
public static function isLoggedIn(): bool
{
return self::id() !== null;
}
/** Check if the current user has one of the given roles otherwise redirect to home */
public static function checkRoles(array $roles): void
{
$match = false;
foreach ($roles as $role) {
$match = $match || self::hasRole($role);
}
if (!$match) {
Http::redirect('/');
}
}
/** Check if the current user has the given role otherwise redirect to home */
public static function checkRole(string $role): void
{
if (!self::hasRole($role)) {
Http::redirect('/');
}
}
/** Check if the current user has the requested role */
public static function hasRole(string $role): bool
{
if (!self::isLoggedIn()) {
return false;
}
return self::userHasRole(self::id(), $role);
}
/** Check if the given user has the requested role */
public static function userHasRole(int $userId, string $role): bool
{
// Check if the role and userId combination is already in the cache
$cacheKey = $role . '-' . strval($userId);
if (in_array($cacheKey, self::$roleCache, true)) {
return self::$roleCache[$cacheKey];
}
$role = Role::findByName($role);
if ($role->getId() === null) {
self::$roleCache[$cacheKey] = false;
return false;
}
$userRole = UserRole::findByUserAndRoleId($userId, $role->getId());
if ($userRole->getId() === null) {
self::$roleCache[$cacheKey] = false;
return false;
}
self::$roleCache[$cacheKey] = true;
return true;
}
/** Check if the given password for the given user */
public static function isPasswordValid(string $username, string $password): bool
{
$user = User::findByUsername($username);
// Return false if the password is not set
if ($user->getPassword() === null) {
return false;
}
// Verify the password
return password_verify($password, $user->getPassword());
}
/** Hash the given password */
public static function hashPassword(string $password): string
{
return password_hash($password, PASSWORD_DEFAULT);
}
}