Commit 56a76739 authored by Administrator's avatar Administrator

Update 1 files via Son of Anton

parent bce237d3
...@@ -5,45 +5,56 @@ namespace App\Core; ...@@ -5,45 +5,56 @@ namespace App\Core;
final class CSRF final class CSRF
{ {
private static string $tokenKey = '_csrf_token'; /**
* Generate a new CSRF token and store in session.
* Only generates if one doesn't already exist.
*/
public static function generate(): string public static function generate(): string
{ {
$session = App::getInstance()->session();
$existing = $session->get('_csrf_token');
if ($existing && is_string($existing) && strlen($existing) > 10) {
return $existing;
}
$token = bin2hex(random_bytes(32)); $token = bin2hex(random_bytes(32));
$_SESSION[self::$tokenKey] = $token; $session->set('_csrf_token', $token);
return $token; return $token;
} }
/**
* Get current token, or generate one.
*/
public static function token(): string public static function token(): string
{ {
if (empty($_SESSION[self::$tokenKey])) { return self::generate();
return self::generate();
}
return $_SESSION[self::$tokenKey];
} }
public static function validate(?string $token): bool /**
* Validate a submitted token.
*/
public static function validate(string $token): bool
{ {
if ($token === null || $token === '') { if ($token === '') {
return false; return false;
} }
$sessionToken = $_SESSION[self::$tokenKey] ?? ''; $session = App::getInstance()->session();
if ($sessionToken === '') { $stored = $session->get('_csrf_token');
if (!$stored || !is_string($stored)) {
return false; return false;
} }
return hash_equals($sessionToken, $token); return hash_equals($stored, $token);
} }
/**
* Return hidden input field.
*/
public static function field(): string public static function field(): string
{ {
return '<input type="hidden" name="_csrf_token" value="' . htmlspecialchars(self::token(), ENT_QUOTES, 'UTF-8') . '">'; return '<input type="hidden" name="_csrf_token" value="' . htmlspecialchars(self::token(), ENT_QUOTES, 'UTF-8') . '">';
} }
// Regenerate token after successful validation (prevents reuse)
public static function regenerate(): void
{
self::generate();
}
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment