45 lines
1.3 KiB
PHP
45 lines
1.3 KiB
PHP
<?php
|
|
namespace Misuzu;
|
|
|
|
use Index\CsrfToken;
|
|
|
|
final class CSRF {
|
|
private static ?CsrfToken $instance = null;
|
|
private static string $secretKey = '';
|
|
|
|
public static function available(): bool {
|
|
return self::$instance !== null;
|
|
}
|
|
|
|
public static function create(string $identity, ?string $secretKey = null): CsrfToken {
|
|
if($secretKey === null)
|
|
$secretKey = self::$secretKey;
|
|
else
|
|
self::$secretKey = $secretKey;
|
|
|
|
return new CsrfToken($secretKey, $identity);
|
|
}
|
|
|
|
public static function init(string $secretKey, string $identity): void {
|
|
self::$instance = self::create($identity, $secretKey);
|
|
}
|
|
|
|
public static function validate(string $token, int $tolerance = -1): bool {
|
|
return self::$instance?->verifyToken($token, $tolerance) ?? false;
|
|
}
|
|
|
|
public static function token(): string {
|
|
return self::$instance?->createToken() ?? '';
|
|
}
|
|
|
|
public static function validateRequest(int $tolerance = -1): bool {
|
|
if(self::$instance === null)
|
|
return false;
|
|
|
|
$token = (string)filter_input(INPUT_POST, '_csrf');
|
|
if(empty($token))
|
|
$token = (string)filter_input(INPUT_GET, 'csrf');
|
|
|
|
return self::$instance->verifyToken($token, $tolerance);
|
|
}
|
|
}
|