1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace kalanis\kw_forms\JWT; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
use Exception; |
7
|
|
|
use Firebase\JWT\JWT; |
8
|
|
|
use Firebase\JWT\Key; |
9
|
|
|
|
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class Token |
13
|
|
|
* @package kalanis\kw_forms\JWT |
14
|
|
|
* Javascript Web Token - class for setting and make checks |
15
|
|
|
* @codeCoverageIgnore dependency on remote library |
16
|
|
|
*/ |
17
|
|
|
class Token |
18
|
|
|
{ |
19
|
|
|
protected static string $domain = ''; |
20
|
|
|
protected static string $privateKey = ''; |
21
|
|
|
protected static string $lastError = ''; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Initialize library - set somewhere in bootstrap alongside the other configurations |
25
|
|
|
* @param string $privateKey |
26
|
|
|
* @param string $domain |
27
|
|
|
*/ |
28
|
|
|
public static function setInitials(string $privateKey, string $domain): void |
29
|
|
|
{ |
30
|
|
|
static::$privateKey = $privateKey; |
31
|
|
|
static::$domain = $domain; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Generate JWT token and user data |
36
|
|
|
* |
37
|
|
|
* @param array<string, string> $tokenData |
38
|
|
|
* @param int $ttl |
39
|
|
|
* @return string |
40
|
|
|
*/ |
41
|
|
|
public static function getJWTToken(array $tokenData, int $ttl = 7200): string |
42
|
|
|
{ |
43
|
|
|
$time = time(); |
44
|
|
|
$tokenData['iss'] = static::$domain; |
45
|
|
|
$tokenData['iat'] = $time; |
46
|
|
|
$tokenData['exp'] = $time + $ttl; |
47
|
|
|
|
48
|
|
|
return JWT::encode($tokenData, static::$privateKey, 'HS256'); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param string $token |
53
|
|
|
* @return array<string, string> |
54
|
|
|
*/ |
55
|
|
|
public static function decodeJWTToken(string $token): array |
56
|
|
|
{ |
57
|
|
|
try { |
58
|
|
|
$decoded = (array) JWT::decode($token, new Key(static::$privateKey, 'HS256')); |
59
|
|
|
if (static::$domain != $decoded['iss']) { |
60
|
|
|
throw new Exception('Token was not issued for this site.'); |
61
|
|
|
} |
62
|
|
|
} catch (Exception $ex) { |
63
|
|
|
static::$lastError = 'Token Error: ' . $ex->getMessage(); |
64
|
|
|
$decoded = []; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $decoded; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @return string |
72
|
|
|
*/ |
73
|
|
|
public static function getLastError(): string |
74
|
|
|
{ |
75
|
|
|
return static::$lastError; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|