-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAuthKeyGenerator.php
77 lines (70 loc) · 2.29 KB
/
AuthKeyGenerator.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
<?php
namespace Authentication;
use Database\TableManagers\UserTableManager;
use Exception;
use Exceptions\HttpExceptions\ExpiredTokenException;
use Exceptions\HttpExceptions\HttpException;
use Exceptions\HttpExceptions\InvalidTokenException;
use Models\User;
use Utils\JWT;
class AuthKeyGenerator
{
/**
* Encodes a JWK token.
* @param User $user The user to encode in the JWK token.
* @param int $exp The expiration time of the token in seconds.
* @return string The encoded JWK token.
*/
public static function encodeJWK(User $user, int $exp = 3600): string
{
$config = include __DIR__ . '/../config/keys.php';
$secretKey = $config['secret_key'];
$payload = array(
"userId" => $user->getId(),
"username" => $user->getUsername(),
"email" => $user->getEmail(),
"iat" => time(),
"exp" => time() + $exp
);
return JWT::encode($payload, $secretKey);
}
/**
* Decodes a JWK token.
*
* @param string $jwk The JWK token to decode.
* @return array The decoded JWK token.
* @throws HttpException
*/
public static function decodeJWK(string $jwk): array
{
$config = include __DIR__ . '/../config/keys.php';
$secretKey = $config['secret_key'];
try {
$decoded = JWT::decode($jwk, $secretKey);
return (array)$decoded;
} catch (Exception $e) {
throw new InvalidTokenException();
}
}
/**
* Fetches the user from the database using the JWK token.
* @throws HttpException
* @throws InvalidTokenException
*/
public static function getUserFromToken(string $jwk, bool $expires = true): User
{
$decoded = self::decodeJWK($jwk);
$userId = $decoded['userId'];
$username = $decoded['username'];
$email = $decoded['email'];
$userTableManager = UserTableManager::GetInstance();
$user = $userTableManager::getUserById($userId);
if ($user === null || $user->getUsername() !== $username || $user->getEmail() !== $email) {
throw new InvalidTokenException();
}
if ($expires && $decoded['exp'] < time()) {
throw new ExpiredTokenException();
}
return $user;
}
}