32 lines
763 B
PHP
32 lines
763 B
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Core;
|
|
|
|
final class Csrf
|
|
{
|
|
public static function ensureToken(): string
|
|
{
|
|
if (session_status() !== PHP_SESSION_ACTIVE) {
|
|
session_start();
|
|
}
|
|
|
|
if (empty($_SESSION['csrf_token'])) {
|
|
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
|
|
}
|
|
|
|
return (string) $_SESSION['csrf_token'];
|
|
}
|
|
|
|
public static function assertPayload(array $payload): void
|
|
{
|
|
$expected = self::ensureToken();
|
|
$provided = (string) ($payload['csrf_token'] ?? '');
|
|
|
|
if ($provided === '' || !hash_equals($expected, $provided)) {
|
|
JsonResponse::send(403, ['error' => 'Jeton de sécurité invalide. Rechargez la page.']);
|
|
}
|
|
}
|
|
}
|