This commit is contained in:
@@ -53,6 +53,32 @@ function require_same_origin_request(): void
|
||||
}
|
||||
}
|
||||
|
||||
function csrf_token(): string
|
||||
{
|
||||
if (empty($_SESSION['csrf_token']) || !is_string($_SESSION['csrf_token'])) {
|
||||
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
return $_SESSION['csrf_token'];
|
||||
}
|
||||
|
||||
function print_csrf_script(): void
|
||||
{
|
||||
echo '<script>window.csrfToken = ' . json_encode(csrf_token()) . ';</script>';
|
||||
}
|
||||
|
||||
function require_csrf_token(): void
|
||||
{
|
||||
if (!in_array($_SERVER['REQUEST_METHOD'] ?? 'GET', ['POST', 'PUT', 'PATCH', 'DELETE'], true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$token = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? $_POST['csrf_token'] ?? '';
|
||||
if (empty($_SESSION['csrf_token']) || !is_string($token) || !hash_equals($_SESSION['csrf_token'], $token)) {
|
||||
json_response(['success' => false, 'message' => 'Invalid CSRF token.'], 403);
|
||||
}
|
||||
}
|
||||
|
||||
function require_logged_in(): void
|
||||
{
|
||||
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || empty($_SESSION['id'])) {
|
||||
|
||||
Reference in New Issue
Block a user