-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAuth.php
More file actions
84 lines (68 loc) · 2.1 KB
/
Copy pathAuth.php
File metadata and controls
84 lines (68 loc) · 2.1 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
<?php
declare(strict_types=1);
namespace Zero\Lib\Auth;
use App\Models\User;
class Auth
{
public const COOKIE = 'auth_token';
public const DEFAULT_TTL = 604800; // 7 days
/**
* Issue a JWT for the provided payload and queue it as an HTTP-only cookie.
*/
public static function login(array $payload, int $ttl = self::DEFAULT_TTL): void
{
$configuredTtl = (int) (config('auth.token_ttl') ?? self::DEFAULT_TTL);
if ($ttl === self::DEFAULT_TTL) {
$ttl = $configuredTtl;
}
$ttl = max(60, $ttl);
$token = Jwt::encode($payload, $ttl);
self::queueCookie($token, $ttl);
$_COOKIE[self::COOKIE] = $token;
}
/**
* Remove the authentication token cookie.
*/
public static function logout(): void
{
self::queueCookie('', -3600);
unset($_COOKIE[self::COOKIE]);
}
/**
* Retrieve the decoded token payload for the current user.
*/
public static function user(): mixed
{
$token = $_COOKIE[self::COOKIE] ?? null;
$payload = Jwt::decode($token);
if ($payload === null) {
self::logout();
return false;
}
return User::query()->find($payload['sub']) ?: null;
}
/**
* Convenience accessor for the subject identifier.
*
* Reads the subject straight from the verified token payload rather than
* from the User model (which has no `sub` key), so it returns the
* authenticated user's id, or null when there is no valid token.
*/
public static function id(): mixed
{
$payload = Jwt::decode($_COOKIE[self::COOKIE] ?? null);
return $payload['sub'] ?? null;
}
protected static function queueCookie(string $value, int $ttl): void
{
$expires = time() + $ttl;
$secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
setcookie(self::COOKIE, $value, [
'expires' => $expires,
'path' => '/',
'secure' => $secure,
'httponly' => true,
'samesite' => 'Lax',
]);
}
}