mirror of
https://github.com/postfixadmin/postfixadmin.git
synced 2026-11-20 23:43:26 +03:00
Improve CSRF invalid error page - Replaces the raw hardcoded error with localized PALANG text. - Provides a simple Continue link back to main.php Related to the 4.0 branch fix in PR #1055.
46 lines
1.3 KiB
PHP
46 lines
1.3 KiB
PHP
<?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;
|
|
}
|
|
|
|
}
|