-
Notifications
You must be signed in to change notification settings - Fork 325
Expand file tree
/
Copy pathCsrfToken.php
More file actions
45 lines (38 loc) · 1.25 KB
/
Copy pathCsrfToken.php
File metadata and controls
45 lines (38 loc) · 1.25 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
<?php
class CsrfToken
{
public static function generate(): string
{
if (!isset($_SESSION['CSRF_Tokens']) || !is_array($_SESSION['CSRF_Tokens'])) {
$_SESSION['CSRF_Tokens'] = [];
}
// remove any expired tokens
foreach ($_SESSION['CSRF_Tokens'] as $key => $value) {
if ($value < (time())) {
unset($_SESSION['CSRF_Tokens'][$key]);
}
}
$token = bin2hex(random_bytes(16));
$_SESSION['CSRF_Tokens'][$token] = (time() + 3600); // is an hour an acceptable expiry time?
return $token;
}
/**
* @param string $token
* @return bool
* @throws CsrfInvalidException
*/
public static function assertValid(string $token): bool
{
if (!isset($_SESSION['CSRF_Tokens']) || !is_array($_SESSION['CSRF_Tokens'])) {
$_SESSION['CSRF_Tokens'] = [];
}
$value = (int)($_SESSION['CSRF_Tokens'][$token] ?? 0);
// token can only be used once.
unset($_SESSION['CSRF_Tokens'][$token]);
// token cannot have expired
if ($value < time()) {
throw new CsrfInvalidException("Invalid CSRF token - try refreshing the page and try again?");
}
return true;
}
}