You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/AdminCsrf.php

66 lines
1.8 KiB
PHTML

<?php
namespace App\Services;
use App\Utils\Cookie;
use Psr\Http\Message\ServerRequestInterface;
final class AdminCsrf
{
public const HEADER_NAME = 'X-Admin-CSRF-Token';
public const FORM_FIELD = '_admin_csrf';
private const SESSION_PREFIX = 'admin_csrf_token_';
public static function token()
{
Cookie::startSession();
$sessionKey = self::sessionKey();
$token = isset($_SESSION[$sessionKey]) ? (string) $_SESSION[$sessionKey] : '';
if (preg_match('/^[a-f0-9]{64}$/', $token) !== 1) {
$token = bin2hex(random_bytes(32));
$_SESSION[$sessionKey] = $token;
}
if (session_status() === PHP_SESSION_ACTIVE) {
session_write_close();
}
return $token;
}
public static function verify(ServerRequestInterface $request)
{
$provided = trim((string) $request->getHeaderLine(self::HEADER_NAME));
if ($provided === '') {
$body = $request->getParsedBody();
if (is_array($body)) {
$candidate = isset($body[self::FORM_FIELD])
? $body[self::FORM_FIELD]
: (isset($body['_csrf']) ? $body['_csrf'] : '');
$provided = is_scalar($candidate) ? trim((string) $candidate) : '';
}
}
if (preg_match('/^[a-f0-9]{64}$/', $provided) !== 1) {
return false;
}
return hash_equals(self::token(), $provided);
}
public static function requiresProtection($method)
{
return in_array(strtoupper((string) $method), ['POST', 'PUT', 'PATCH', 'DELETE'], true);
}
private static function sessionKey()
{
$user = Auth::getUser();
$userId = is_object($user) && isset($user->id) ? max(0, (int) $user->id) : 0;
return self::SESSION_PREFIX . $userId;
}
}