misuzu/src/CSRF.php

46 lines
1.3 KiB
PHP
Raw Normal View History

2019-12-11 19:10:54 +01:00
<?php
namespace Misuzu;
2024-10-05 02:40:29 +00:00
use Index\CsrfToken;
2019-12-11 19:10:54 +01:00
final class CSRF {
private static ?CsrfToken $instance = null;
2024-07-20 19:35:50 +00:00
private static string $secretKey = '';
public static function available(): bool {
return self::$instance !== null;
}
2024-10-05 02:40:29 +00:00
public static function create(string $identity, ?string $secretKey = null): CsrfToken {
2024-07-20 19:35:50 +00:00
if($secretKey === null)
$secretKey = self::$secretKey;
else
self::$secretKey = $secretKey;
2024-10-05 02:40:29 +00:00
return new CsrfToken($secretKey, $identity);
2024-07-20 19:35:50 +00:00
}
2019-12-11 19:10:54 +01:00
2023-07-11 22:13:56 +00:00
public static function init(string $secretKey, string $identity): void {
2024-07-20 19:35:50 +00:00
self::$instance = self::create($identity, $secretKey);
2019-12-11 19:10:54 +01:00
}
2023-07-11 22:13:56 +00:00
public static function validate(string $token, int $tolerance = -1): bool {
return self::$instance?->verifyToken($token, $tolerance) ?? false;
2019-12-11 19:10:54 +01:00
}
2023-07-11 22:13:56 +00:00
public static function token(): string {
return self::$instance?->createToken() ?? '';
2019-12-11 19:10:54 +01:00
}
2023-07-11 22:13:56 +00:00
public static function validateRequest(int $tolerance = -1): bool {
if(self::$instance === null)
return false;
2023-07-12 19:14:40 +00:00
$token = (string)filter_input(INPUT_POST, '_csrf');
2023-07-11 20:51:24 +00:00
if(empty($token))
2023-07-12 19:14:40 +00:00
$token = (string)filter_input(INPUT_GET, 'csrf');
2019-12-11 19:10:54 +01:00
2023-07-11 22:13:56 +00:00
return self::$instance->verifyToken($token, $tolerance);
2019-12-11 19:10:54 +01:00
}
}