Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
94.41% |
304 / 322 |
|
88.24% |
30 / 34 |
CRAP | |
0.00% |
0 / 1 |
| AuthUtils | |
94.41% |
304 / 322 |
|
88.24% |
30 / 34 |
121.47 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| authenticate | |
100.00% |
20 / 20 |
|
100.00% |
1 / 1 |
6 | |||
| validateAccessToken | |
100.00% |
30 / 30 |
|
100.00% |
1 / 1 |
7 | |||
| issueRefreshToken | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
1 | |||
| generateRefreshToken | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| revokeAllRefreshTokens | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
2 | |||
| createRefreshTokenCookie | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
2 | |||
| getRefreshToken | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
6 | |||
| findRefreshTokenByHash | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
2 | |||
| refreshSessionFromRefreshToken | |
78.57% |
33 / 42 |
|
0.00% |
0 / 1 |
15.93 | |||
| startSessionForUser | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
| resolveUsernameOrEmail | |
100.00% |
16 / 16 |
|
100.00% |
1 / 1 |
7 | |||
| hasPermission | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
4 | |||
| hasUserPermission | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
| getUserPermissionMap | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
6 | |||
| hasRolePermission | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
| getRolePermissionMap | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
7 | |||
| getCurrentUser | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| getCurrentAuthUser | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| getTokenUser | |
70.00% |
7 / 10 |
|
0.00% |
0 / 1 |
5.68 | |||
| getSessionUser | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| setSessionUser | |
100.00% |
32 / 32 |
|
100.00% |
1 / 1 |
7 | |||
| getSessionAuthUser | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| setSessionAuthUser | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |||
| getUserByUsername | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
4 | |||
| getAuthenticatedRoles | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| isRoleIdAuthenticated | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| hasRoleEditPermission | |
94.44% |
17 / 18 |
|
0.00% |
0 / 1 |
7.01 | |||
| isUsernameAllowed | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| isUsernameUnique | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
8 | |||
| isPasswordAllowed | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| getUserAvatar | |
100.00% |
16 / 16 |
|
100.00% |
1 / 1 |
3 | |||
| hashPassword | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| verifyPassword | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace Olz\Common\Utils; |
| 4 | |
| 5 | use Doctrine\ORM\OptimisticLockException; |
| 6 | use Olz\Entity\AccessToken; |
| 7 | use Olz\Entity\AuthRequest; |
| 8 | use Olz\Entity\Roles\Role; |
| 9 | use Olz\Entity\Users\User; |
| 10 | use Olz\Exceptions\AuthBlockedException; |
| 11 | use Olz\Exceptions\InvalidCredentialsException; |
| 12 | use Symfony\Component\HttpFoundation\Cookie; |
| 13 | use Symfony\Component\HttpFoundation\RequestStack; |
| 14 | |
| 15 | class AuthUtils { |
| 16 | use WithUtilsTrait; |
| 17 | |
| 18 | public const MAX_LOOP = 5; |
| 19 | |
| 20 | public const REFRESH_TOKEN_COOKIE = 'olz_refresh_token'; |
| 21 | protected const REFRESH_TOKEN_PURPOSE = 'refresh'; |
| 22 | public const REFRESH_TOKEN_TTL = 31536000; // 1 year, slid forward on every use |
| 23 | /** How long the previous refresh token is still accepted after rotation. */ |
| 24 | public const REFRESH_TOKEN_GRACE = 60; // 1 minute |
| 25 | public const SESSION_TIMEOUT = 43200; // 12 hours |
| 26 | |
| 27 | /** @var array<int, array<string, bool>> */ |
| 28 | protected array $cached_permission_map_by_user = []; |
| 29 | /** @var array<int, array<string, bool>> */ |
| 30 | protected array $cached_permission_map_by_role = []; |
| 31 | /** @var array<string, User> */ |
| 32 | protected array $cached_users = []; |
| 33 | |
| 34 | public function __construct( |
| 35 | protected ?RequestStack $request_stack = null, |
| 36 | ) { |
| 37 | } |
| 38 | |
| 39 | public function authenticate(string $username_or_email, string $password): User { |
| 40 | $ip_address = $this->server()['REMOTE_ADDR']; |
| 41 | $auth_request_repo = $this->entityManager()->getRepository(AuthRequest::class); |
| 42 | |
| 43 | // If there are invalid credentials provided too often, we block. |
| 44 | $num_remaining_attempts = $auth_request_repo->numRemainingAttempts($ip_address); |
| 45 | if ($num_remaining_attempts <= 0) { |
| 46 | $message = "Login attempt from blocked IP: {$ip_address} (user: {$username_or_email})."; |
| 47 | $this->log()->notice($message); |
| 48 | $auth_request_repo->addAuthRequest($ip_address, 'BLOCKED', $username_or_email); |
| 49 | throw new AuthBlockedException($message); |
| 50 | } |
| 51 | |
| 52 | $user = $this->resolveUsernameOrEmail($username_or_email); |
| 53 | |
| 54 | // If the password is wrong, authentication fails. |
| 55 | $hash = $user?->getPasswordHash(); |
| 56 | if (!$user || !$password || !$hash || !$this->verifyPassword($password, $hash)) { |
| 57 | $message = "Login attempt with invalid credentials from IP: {$ip_address} (user: {$username_or_email})."; |
| 58 | $this->log()->notice($message); |
| 59 | $auth_request_repo->addAuthRequest($ip_address, 'INVALID_CREDENTIALS', $username_or_email); |
| 60 | throw new InvalidCredentialsException($message, $num_remaining_attempts); |
| 61 | } |
| 62 | |
| 63 | $this->log()->info("User login successful: {$username_or_email}"); |
| 64 | $this->log()->info(" Auth: {$user->getPermissions()}"); |
| 65 | $this->log()->info(" Root: {$user->getRoot()}"); |
| 66 | $auth_request_repo->addAuthRequest($ip_address, 'AUTHENTICATED', $username_or_email); |
| 67 | return $user; |
| 68 | } |
| 69 | |
| 70 | public function validateAccessToken(string $access_token): ?User { |
| 71 | $ip_address = $this->server()['REMOTE_ADDR']; |
| 72 | $auth_request_repo = $this->entityManager()->getRepository(AuthRequest::class); |
| 73 | |
| 74 | // If there are invalid credentials provided too often, we block. |
| 75 | $can_validate = $auth_request_repo->canValidateAccessToken($ip_address); |
| 76 | if (!$can_validate) { |
| 77 | $message = "Access token validation from blocked IP: {$ip_address}."; |
| 78 | $this->log()->notice($message); |
| 79 | $auth_request_repo->addAuthRequest($ip_address, 'TOKEN_BLOCKED', ''); |
| 80 | throw new AuthBlockedException($message); |
| 81 | } |
| 82 | |
| 83 | $access_token_repo = $this->entityManager()->getRepository(AccessToken::class); |
| 84 | $access_token = $access_token_repo->findOneBy(['token' => $access_token]); |
| 85 | $user = $access_token ? $access_token->getUser() : null; |
| 86 | |
| 87 | // If the access token is invalid, authentication fails. |
| 88 | if (!$access_token || !$user) { |
| 89 | $message = "Invalid access token validation from IP: {$ip_address}."; |
| 90 | $this->log()->notice($message); |
| 91 | $auth_request_repo->addAuthRequest($ip_address, 'INVALID_TOKEN', ''); |
| 92 | throw new InvalidCredentialsException($message); |
| 93 | } |
| 94 | |
| 95 | $now = $this->dateUtils()->getIsoNow(); |
| 96 | $expires_at = $access_token->getExpiresAt(); |
| 97 | $is_access_token_expired = ( |
| 98 | $expires_at !== null |
| 99 | && $expires_at->format('Y-m-d H:i:s') < $now |
| 100 | ); |
| 101 | |
| 102 | // If the access token is expired, authentication fails. |
| 103 | if ($is_access_token_expired) { |
| 104 | $message = "Expired access token validation from IP: {$ip_address}."; |
| 105 | $this->log()->notice($message); |
| 106 | $auth_request_repo->addAuthRequest($ip_address, 'EXPIRED_TOKEN', ''); |
| 107 | throw new InvalidCredentialsException($message); |
| 108 | } |
| 109 | |
| 110 | $this->log()->info("Token validation successful: {$access_token->getId()}"); |
| 111 | $auth_request_repo->addAuthRequest($ip_address, 'TOKEN_VALIDATED', $user->getUsername()); |
| 112 | return $user; |
| 113 | } |
| 114 | |
| 115 | /** |
| 116 | * Creates a new refresh token for the user and returns the raw token, which |
| 117 | * must be put into the (HttpOnly) cookie. Only a SHA-256 hash of it is stored. |
| 118 | * Plain SHA-256 is enough here (unlike passwords) because the token is a |
| 119 | * high-entropy random value, so there is nothing to brute-force or precompute. |
| 120 | */ |
| 121 | public function issueRefreshToken(User $user): string { |
| 122 | $raw_token = $this->generateRefreshToken(); |
| 123 | $now = new \DateTime($this->dateUtils()->getIsoNow()); |
| 124 | $access_token = new AccessToken(); |
| 125 | $access_token->setUser($user); |
| 126 | $access_token->setPurpose(self::REFRESH_TOKEN_PURPOSE); |
| 127 | $access_token->setToken(hash('sha256', $raw_token)); |
| 128 | $access_token->setCreatedAt($now); |
| 129 | $access_token->setExpiresAt((clone $now)->modify('+'.self::REFRESH_TOKEN_TTL.' seconds')); |
| 130 | $this->entityManager()->persist($access_token); |
| 131 | $this->entityManager()->flush(); |
| 132 | return $raw_token; |
| 133 | } |
| 134 | |
| 135 | /** Generates a new high-entropy (raw) refresh token. */ |
| 136 | protected function generateRefreshToken(): string { |
| 137 | return $this->generalUtils()->base64EncodeUrl(openssl_random_pseudo_bytes(32)); |
| 138 | } |
| 139 | |
| 140 | public function revokeAllRefreshTokens(User $user): void { |
| 141 | $repo = $this->entityManager()->getRepository(AccessToken::class); |
| 142 | $access_tokens = $repo->findBy([ |
| 143 | 'user' => $user, |
| 144 | 'purpose' => self::REFRESH_TOKEN_PURPOSE, |
| 145 | ]); |
| 146 | foreach ($access_tokens as $access_token) { |
| 147 | $this->entityManager()->remove($access_token); |
| 148 | } |
| 149 | $this->entityManager()->flush(); |
| 150 | } |
| 151 | |
| 152 | /** Creates the refresh token cookie; `null` creates a cookie that clears it. */ |
| 153 | public function createRefreshTokenCookie(?string $raw_token): Cookie { |
| 154 | $expires_at = $raw_token === null ? 1 : time() + self::REFRESH_TOKEN_TTL; |
| 155 | return Cookie::create(self::REFRESH_TOKEN_COOKIE) |
| 156 | ->withValue($raw_token ?? '') |
| 157 | ->withExpires($expires_at) |
| 158 | ->withPath('/') |
| 159 | ->withSecure($this->request_stack?->getCurrentRequest()?->isSecure() ?? true) |
| 160 | ->withHttpOnly(true) |
| 161 | ->withSameSite(Cookie::SAMESITE_LAX) |
| 162 | ; |
| 163 | } |
| 164 | |
| 165 | public function getRefreshToken(): ?AccessToken { |
| 166 | $request = $this->request_stack?->getCurrentRequest(); |
| 167 | $raw_token = $request?->cookies->get(self::REFRESH_TOKEN_COOKIE); |
| 168 | if (!$raw_token) { |
| 169 | return null; |
| 170 | } |
| 171 | return $this->findRefreshTokenByHash(hash('sha256', $raw_token)); |
| 172 | } |
| 173 | |
| 174 | /** |
| 175 | * Finds the refresh token row by the hash of the current or of the previous |
| 176 | * (rotated) raw token. |
| 177 | */ |
| 178 | public function findRefreshTokenByHash(string $token_hash): ?AccessToken { |
| 179 | $repo = $this->entityManager()->getRepository(AccessToken::class); |
| 180 | $refresh_token = $repo->findOneBy([ |
| 181 | 'token' => $token_hash, |
| 182 | 'purpose' => self::REFRESH_TOKEN_PURPOSE, |
| 183 | ]); |
| 184 | if ($refresh_token !== null) { |
| 185 | return $refresh_token; |
| 186 | } |
| 187 | return $repo->findOneBy([ |
| 188 | 'old_token' => $token_hash, |
| 189 | 'purpose' => self::REFRESH_TOKEN_PURPOSE, |
| 190 | ]); |
| 191 | } |
| 192 | |
| 193 | /** |
| 194 | * Restores the session from the given (raw) refresh token, rotating the |
| 195 | * refresh token in the process. This is used by the `refresh` API endpoint, |
| 196 | * both whenever a request failed due to an invalid session (see `OlzApi.ts`) |
| 197 | * and on page load (see `OlzLoginModal.tsx`), where the page is rendered as |
| 198 | * logged out and then reloaded once the session has been restored. |
| 199 | * |
| 200 | * Returns the newly issued (raw) refresh token which must be put into the |
| 201 | * cookie, or null if no cookie change is needed (the session is already |
| 202 | * valid, or a concurrent request already rotated the token). |
| 203 | * |
| 204 | * @throws \Exception if the session cannot be restored |
| 205 | * (missing, unknown, expired, or re-used refresh token) |
| 206 | */ |
| 207 | public function refreshSessionFromRefreshToken(?string $raw_token): ?string { |
| 208 | if ($this->session()->has('user')) { |
| 209 | return null; |
| 210 | } |
| 211 | if ($raw_token === null || $raw_token === '') { |
| 212 | throw new \Exception('No refresh token provided.'); |
| 213 | } |
| 214 | $token_hash = hash('sha256', $raw_token); |
| 215 | $refresh_token = $this->findRefreshTokenByHash($token_hash); |
| 216 | $user = $refresh_token?->getUser(); |
| 217 | if ($refresh_token === null || $user === null) { |
| 218 | throw new \Exception('Invalid refresh token.'); |
| 219 | } |
| 220 | $now = new \DateTime($this->dateUtils()->getIsoNow()); |
| 221 | $expires_at = $refresh_token->getExpiresAt(); |
| 222 | if ($expires_at !== null && $expires_at < $now) { |
| 223 | $this->entityManager()->remove($refresh_token); |
| 224 | $this->entityManager()->flush(); |
| 225 | throw new \Exception('Expired refresh token.'); |
| 226 | } |
| 227 | if ($refresh_token->getToken() !== $token_hash) { |
| 228 | // The previous token is only accepted within a short grace window, |
| 229 | // e.g. for concurrent requests that were in flight when the token |
| 230 | // was rotated. |
| 231 | $rotated_at = $refresh_token->getRotatedAt(); |
| 232 | $grace_end = $rotated_at !== null |
| 233 | ? (clone $rotated_at)->modify('+'.self::REFRESH_TOKEN_GRACE.' seconds') |
| 234 | : null; |
| 235 | $is_within_grace = ($grace_end !== null && $grace_end >= $now); |
| 236 | if (!$is_within_grace) { |
| 237 | // Re-use of an already rotated token: assume it was stolen. |
| 238 | $this->entityManager()->remove($refresh_token); |
| 239 | $this->entityManager()->flush(); |
| 240 | throw new \Exception('Previous refresh token is no longer in the grace window.'); |
| 241 | } |
| 242 | $this->startSessionForUser($user); |
| 243 | return null; |
| 244 | } |
| 245 | // Rotate the refresh token. |
| 246 | $new_raw_token = $this->generateRefreshToken(); |
| 247 | $refresh_token->setOldToken($refresh_token->getToken()); |
| 248 | $refresh_token->setToken(hash('sha256', $new_raw_token)); |
| 249 | $refresh_token->setRotatedAt($now); |
| 250 | $refresh_token->setExpiresAt((clone $now)->modify('+'.self::REFRESH_TOKEN_TTL.' seconds')); |
| 251 | try { |
| 252 | $this->entityManager()->flush(); |
| 253 | } catch (OptimisticLockException $exc) { |
| 254 | // A concurrent request has rotated the token in the meantime. Our |
| 255 | // token is now the previous one, which is within the grace window. |
| 256 | $this->entityManager()->detach($refresh_token); |
| 257 | $current_token = $this->findRefreshTokenByHash($token_hash); |
| 258 | if ($current_token === null) { |
| 259 | throw new \Exception('Refresh token disappeared during concurrent rotation.', 0, $exc); |
| 260 | } |
| 261 | $this->startSessionForUser($user); |
| 262 | return null; |
| 263 | } |
| 264 | $this->startSessionForUser($user); |
| 265 | return $new_raw_token; |
| 266 | } |
| 267 | |
| 268 | protected function startSessionForUser(User $user): void { |
| 269 | $this->session()->resetConfigure(['timeout' => self::SESSION_TIMEOUT]); |
| 270 | $this->setSessionUser($user); |
| 271 | $this->setSessionAuthUser($user); |
| 272 | } |
| 273 | |
| 274 | public function resolveUsernameOrEmail(string $username_or_email): ?User { |
| 275 | $user_repo = $this->entityManager()->getRepository(User::class); |
| 276 | $user = $user_repo->findOneBy(['username' => $username_or_email]); |
| 277 | if (!$user) { |
| 278 | $user = $user_repo->findOneBy(['email' => $username_or_email]); |
| 279 | } |
| 280 | if (!$user) { |
| 281 | $user = $user_repo->findOneBy(['old_username' => $username_or_email]); |
| 282 | } |
| 283 | $res = preg_match( |
| 284 | '/^([a-zA-Z0-9-_\.]+)@olzimmerberg.ch$/', |
| 285 | $username_or_email, |
| 286 | $matches |
| 287 | ); |
| 288 | if (!$user && $res) { |
| 289 | $user = $user_repo->findOneBy(['username' => $matches[1]]); |
| 290 | } |
| 291 | if (!$user && $res) { |
| 292 | $user = $user_repo->findOneBy(['old_username' => $matches[1]]); |
| 293 | } |
| 294 | return $user; |
| 295 | } |
| 296 | |
| 297 | public function hasPermission(string $query, ?User $user = null): bool { |
| 298 | if (!$user) { |
| 299 | $user = $this->getCurrentUser(); |
| 300 | } |
| 301 | $user_permission_map = $this->getUserPermissionMap($user); |
| 302 | $roles = $this->getAuthenticatedRoles($user) ?? []; |
| 303 | $permission_map = [...$user_permission_map]; |
| 304 | foreach ($roles as $role) { |
| 305 | $role_permission_map = $this->getRolePermissionMap($role); |
| 306 | $permission_map = [...$role_permission_map, ...$permission_map]; |
| 307 | } |
| 308 | return ($permission_map['all'] ?? false) || ($permission_map[$query] ?? false); |
| 309 | } |
| 310 | |
| 311 | public function hasUserPermission(string $query, ?User $user): bool { |
| 312 | $permission_map = $this->getUserPermissionMap($user); |
| 313 | return ($permission_map['all'] ?? false) || ($permission_map[$query] ?? false); |
| 314 | } |
| 315 | |
| 316 | /** @return array<string, bool> */ |
| 317 | protected function getUserPermissionMap(?User $user): array { |
| 318 | if (!$user) { |
| 319 | return ['any' => false]; |
| 320 | } |
| 321 | $user_id = $user->getId() ?: 0; |
| 322 | $permission_map = $this->cached_permission_map_by_user[$user_id] ?? null; |
| 323 | if ($permission_map != null) { |
| 324 | return $permission_map; |
| 325 | } |
| 326 | $permission_list = preg_split('/[ ]+/', $user->getPermissions()) ?: []; |
| 327 | $permission_map = ['any' => true]; |
| 328 | foreach ($permission_list as $permission) { |
| 329 | $permission_map[$permission] = true; |
| 330 | } |
| 331 | $this->cached_permission_map_by_user[$user_id] = $permission_map; |
| 332 | return $permission_map; |
| 333 | } |
| 334 | |
| 335 | public function hasRolePermission(string $query, ?Role $role): bool { |
| 336 | $permission_map = $this->getRolePermissionMap($role); |
| 337 | return ($permission_map['all'] ?? false) || ($permission_map[$query] ?? false); |
| 338 | } |
| 339 | |
| 340 | /** @return array<string, bool> */ |
| 341 | protected function getRolePermissionMap(?Role $role): array { |
| 342 | if (!$role || $role->getDeletedAt() !== null) { |
| 343 | return ['any' => false]; |
| 344 | } |
| 345 | $role_id = $role->getId() ?: 0; |
| 346 | $permission_map = $this->cached_permission_map_by_role[$role_id] ?? null; |
| 347 | if ($permission_map != null) { |
| 348 | return $permission_map; |
| 349 | } |
| 350 | $permission_list = preg_split('/[ ]+/', $role->getPermissions()) ?: []; |
| 351 | $permission_map = ['any' => true]; |
| 352 | foreach ($permission_list as $permission) { |
| 353 | $permission_map[$permission] = true; |
| 354 | } |
| 355 | $this->cached_permission_map_by_role[$role_id] = $permission_map; |
| 356 | return $permission_map; |
| 357 | } |
| 358 | |
| 359 | public function getCurrentUser(): ?User { |
| 360 | $user = $this->getTokenUser(); |
| 361 | if ($user) { |
| 362 | return $user; |
| 363 | } |
| 364 | return $this->getSessionUser(); |
| 365 | } |
| 366 | |
| 367 | public function getCurrentAuthUser(): ?User { |
| 368 | return $this->getSessionAuthUser(); |
| 369 | } |
| 370 | |
| 371 | public function getTokenUser(): ?User { |
| 372 | $access_token = $this->getParams()['access_token'] ?? null; |
| 373 | if (!$access_token) { |
| 374 | return null; |
| 375 | } |
| 376 | try { |
| 377 | return $this->validateAccessToken($access_token); |
| 378 | } catch (AuthBlockedException $exc) { |
| 379 | return null; |
| 380 | } catch (InvalidCredentialsException $exc) { |
| 381 | return null; |
| 382 | } catch (\Exception $exc) { |
| 383 | throw $exc; |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | public function getSessionUser(): ?User { |
| 388 | $username = $this->session()->get('user'); |
| 389 | return $this->getUserByUsername($username); |
| 390 | } |
| 391 | |
| 392 | public function setSessionUser(?User $user): void { |
| 393 | if ($user === null) { |
| 394 | $this->session()->delete('auth'); |
| 395 | $this->session()->delete('root'); |
| 396 | $this->session()->delete('user_id'); |
| 397 | $this->session()->delete('user'); |
| 398 | $this->session()->delete('user_name'); |
| 399 | $this->session()->delete('user_permissions'); |
| 400 | $this->session()->delete('user_root'); |
| 401 | $this->session()->delete('user_children'); |
| 402 | return; |
| 403 | } |
| 404 | // Family |
| 405 | $user_repo = $this->entityManager()->getRepository(User::class); |
| 406 | $child_users = $user_repo->findBy(['parent_user' => $user->getId()]); |
| 407 | $children = []; |
| 408 | foreach ($child_users as $child_user) { |
| 409 | $children[] = [ |
| 410 | 'id' => $child_user->getId(), |
| 411 | 'permissions' => $child_user->getPermissionMap(), |
| 412 | 'name' => $child_user->getFullName(), |
| 413 | 'username' => $child_user->getUsername(), |
| 414 | 'root' => $child_user->getRoot() !== '' ? $child_user->getRoot() : './', |
| 415 | ]; |
| 416 | } |
| 417 | $children_json = json_encode($children) ?: '[]'; |
| 418 | |
| 419 | $root = $user->getRoot() !== '' ? $user->getRoot() : './'; |
| 420 | $permission_map_json = json_encode($user->getPermissionMap()) ?: '{}'; |
| 421 | $this->session()->set('auth', $user->getPermissions()); // TODO: Deprecate |
| 422 | $this->session()->set('root', $root); // TODO: Deprecate |
| 423 | $this->session()->set('user_id', "{$user->getId()}"); |
| 424 | $this->session()->set('user', $user->getUsername()); |
| 425 | $this->session()->set('user_name', $user->getFullName()); |
| 426 | $this->session()->set('user_permissions', $permission_map_json); |
| 427 | $this->session()->set('user_root', $root); |
| 428 | $this->session()->set('user_children', $children_json); |
| 429 | } |
| 430 | |
| 431 | public function getSessionAuthUser(): ?User { |
| 432 | $auth_username = $this->session()->get('auth_user'); |
| 433 | return $this->getUserByUsername($auth_username); |
| 434 | } |
| 435 | |
| 436 | public function setSessionAuthUser(?User $user): void { |
| 437 | if ($user === null) { |
| 438 | $this->session()->delete('auth_user'); |
| 439 | $this->session()->delete('auth_user_id'); |
| 440 | return; |
| 441 | } |
| 442 | $this->session()->set('auth_user', $user->getUsername()); |
| 443 | $this->session()->set('auth_user_id', "{$user->getId()}"); |
| 444 | } |
| 445 | |
| 446 | private function getUserByUsername(?string $username): ?User { |
| 447 | if (!$username) { |
| 448 | return null; |
| 449 | } |
| 450 | $cached_user = $this->cached_users[$username] ?? null; |
| 451 | if ($cached_user) { |
| 452 | return $cached_user; |
| 453 | } |
| 454 | $user_repo = $this->entityManager()->getRepository(User::class); |
| 455 | $fetched_user = $user_repo->findOneBy(['username' => $username]); |
| 456 | if ($fetched_user) { |
| 457 | $this->cached_users[$username] = $fetched_user; |
| 458 | } |
| 459 | return $fetched_user; |
| 460 | } |
| 461 | |
| 462 | /** @return ?array<Role> */ |
| 463 | public function getAuthenticatedRoles(?User $user = null): ?array { |
| 464 | if (!$user) { |
| 465 | $user = $this->getCurrentUser(); |
| 466 | } |
| 467 | if (!$user) { |
| 468 | return null; |
| 469 | } |
| 470 | return [...$user->getRoles()]; |
| 471 | } |
| 472 | |
| 473 | public function isRoleIdAuthenticated(int $role_id): bool { |
| 474 | $authenticated_roles = $this->getAuthenticatedRoles() ?? []; |
| 475 | foreach ($authenticated_roles as $authenticated_role) { |
| 476 | if ($authenticated_role->getId() === $role_id) { |
| 477 | return true; |
| 478 | } |
| 479 | } |
| 480 | return false; |
| 481 | } |
| 482 | |
| 483 | public function hasRoleEditPermission(?int $role_id = null): bool { |
| 484 | $user = $this->getCurrentUser(); |
| 485 | if ($this->hasPermission('roles', $user)) { |
| 486 | return true; |
| 487 | } |
| 488 | $auth_roles = $this->getAuthenticatedRoles($user); |
| 489 | $is_role_id_authenticated = []; |
| 490 | foreach (($auth_roles ?? []) as $auth_role) { |
| 491 | if ($auth_role->getDeletedAt() !== null) { |
| 492 | continue; |
| 493 | } |
| 494 | $is_role_id_authenticated[$auth_role->getId()] = true; |
| 495 | } |
| 496 | $role_repo = $this->entityManager()->getRepository(Role::class); |
| 497 | for ($i = 0; $i < self::MAX_LOOP; $i++) { |
| 498 | if ($role_id === null) { |
| 499 | return false; |
| 500 | } |
| 501 | if (($is_role_id_authenticated[$role_id] ?? false) === true) { |
| 502 | return true; |
| 503 | } |
| 504 | $role = $role_repo->findOneBy(['id' => $role_id]); |
| 505 | $role_id = $role?->getParentRoleId() ?? null; |
| 506 | } |
| 507 | return false; |
| 508 | } |
| 509 | |
| 510 | public function isUsernameAllowed(string $username): bool { |
| 511 | // TODO: Underscore & uppercase is disallowed in frontend, but allowed in backend. |
| 512 | return preg_match('/^[a-zA-Z0-9-_\.]+$/', $username) ? true : false; |
| 513 | } |
| 514 | |
| 515 | /** @param ?(User|Role) $existing_entity */ |
| 516 | public function isUsernameUnique(string $username, ?object $existing_entity): bool { |
| 517 | $user_repo = $this->entityManager()->getRepository(User::class); |
| 518 | $role_repo = $this->entityManager()->getRepository(Role::class); |
| 519 | |
| 520 | $same_username_user = $user_repo->findOneBy(['username' => $username]); |
| 521 | $same_old_username_user = $user_repo->findOneBy(['old_username' => $username]); |
| 522 | $same_username_role = $role_repo->findOneBy(['username' => $username]); |
| 523 | $same_old_username_role = $role_repo->findOneBy(['old_username' => $username]); |
| 524 | |
| 525 | $has_conflict = ( |
| 526 | ($same_username_user && ($same_username_user !== $existing_entity)) |
| 527 | || ($same_old_username_user && ($same_old_username_user !== $existing_entity)) |
| 528 | || ($same_username_role && ($same_username_role !== $existing_entity)) |
| 529 | || ($same_old_username_role && ($same_old_username_role !== $existing_entity)) |
| 530 | ); |
| 531 | return !$has_conflict; |
| 532 | } |
| 533 | |
| 534 | public function isPasswordAllowed(string $password): bool { |
| 535 | return strlen($password) >= 8; |
| 536 | } |
| 537 | |
| 538 | /** @return array<string, string> */ |
| 539 | public function getUserAvatar(?User $user): array { |
| 540 | $env_utils = $this->envUtils(); |
| 541 | $code_href = $env_utils->getCodeHref(); |
| 542 | $data_href = $env_utils->getDataHref(); |
| 543 | if (!$user) { |
| 544 | $initials_enc = urlencode('?'); |
| 545 | return ['1x' => "{$code_href}assets/user_initials_{$initials_enc}.svg"]; |
| 546 | } |
| 547 | if ($user->getAvatarImageId()) { |
| 548 | $image_id = $user->getAvatarImageId(); |
| 549 | return [ |
| 550 | '2x' => "{$data_href}img/users/{$user->getId()}/thumb/{$image_id}\$256.jpg", |
| 551 | '1x' => "{$data_href}img/users/{$user->getId()}/thumb/{$image_id}\$128.jpg", |
| 552 | ]; |
| 553 | } |
| 554 | $first_initial = mb_substr($user->getFirstName(), 0, 1); |
| 555 | $last_initial = mb_substr($user->getLastName(), 0, 1); |
| 556 | $initials_enc = urlencode(strtoupper("{$first_initial}{$last_initial}")); |
| 557 | return ['1x' => "{$code_href}assets/user_initials_{$initials_enc}.svg"]; |
| 558 | } |
| 559 | |
| 560 | public function hashPassword(string $password): string { |
| 561 | return password_hash($password, PASSWORD_DEFAULT); |
| 562 | } |
| 563 | |
| 564 | public function verifyPassword(string $password, string $hash): bool { |
| 565 | return password_verify($password, $hash); |
| 566 | } |
| 567 | } |