Nofu/app/utils/CsrfToken.php

39 lines
1.2 KiB
PHP
Raw Permalink Normal View History

2024-06-14 17:20:01 +02:00
<?php
namespace Utils;
class CsrfToken {
/**
* Generate a CSRF token and store it in the session.
*
* This static method generates a CSRF token using random bytes and stores it in the session.
* The generated token is a hexadecimal string with a length of 32 characters.
*
* @return string The generated CSRF token.
*/
public static function generateToken(): string {
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;
return $token;
}
/**
* Validate a CSRF token against the one stored in the session.
*
* This static method validates a given CSRF token against the one stored in the session.
* It returns true if the provided token matches the one in the session; otherwise, it returns false.
*
* @param string $token The CSRF token to be validated.
*
* @return bool True if the provided token is valid; otherwise, false.
*/
public static function validateToken(string $token): bool {
if (isset($_SESSION['csrf_token']) && $_SESSION['csrf_token'] === $token) {
return true;
} else {
return false;
}
}
}