2016-11-29 22:27:19 +00:00
|
|
|
<?php
|
2025-03-29 10:50:03 +00:00
|
|
|
|
2022-02-14 20:48:15 -08:00
|
|
|
/**
|
|
|
|
|
* Validates and generates CSRF tokens.
|
2016-11-29 22:27:19 +00:00
|
|
|
*
|
2022-02-14 20:48:15 -08:00
|
|
|
* @package NamelessMC\Core
|
|
|
|
|
* @author Samerton
|
|
|
|
|
* @version 2.0.0-pr8
|
|
|
|
|
* @license MIT
|
2016-11-29 22:27:19 +00:00
|
|
|
*/
|
2024-03-09 03:19:55 -08:00
|
|
|
class Token
|
|
|
|
|
{
|
2021-04-12 18:36:34 -07:00
|
|
|
/**
|
|
|
|
|
* Get current form token.
|
|
|
|
|
*
|
|
|
|
|
* @return string current form token.
|
|
|
|
|
*/
|
2024-03-09 03:19:55 -08:00
|
|
|
public static function get(): string
|
|
|
|
|
{
|
2022-06-12 20:35:45 -06:00
|
|
|
$tokenName = Config::get('session.token_name');
|
2020-12-13 19:38:04 +01:00
|
|
|
|
|
|
|
|
// Return if it already exists
|
2020-12-13 20:42:04 -08:00
|
|
|
if (Session::exists($tokenName)) {
|
2020-12-13 19:38:04 +01:00
|
|
|
return Session::get($tokenName);
|
2020-12-13 20:42:04 -08:00
|
|
|
}
|
2021-05-14 14:09:14 -07:00
|
|
|
|
2022-02-14 20:48:15 -08:00
|
|
|
// Otherwise, generate a new one
|
2021-05-14 14:09:14 -07:00
|
|
|
self::generate();
|
2021-12-07 22:14:12 -08:00
|
|
|
|
2021-05-14 14:09:14 -07:00
|
|
|
return self::get();
|
2020-12-13 19:38:04 +01:00
|
|
|
}
|
|
|
|
|
|
2021-12-07 22:14:12 -08:00
|
|
|
/**
|
2024-03-09 03:19:55 -08:00
|
|
|
* Generate a form token and store in a session variable.
|
2021-12-07 22:14:12 -08:00
|
|
|
*/
|
2024-03-09 03:19:55 -08:00
|
|
|
public static function generate(): void
|
|
|
|
|
{
|
2021-12-07 22:14:12 -08:00
|
|
|
// Generate random token using md5
|
2022-06-12 20:35:45 -06:00
|
|
|
Session::put(Config::get('session.token_name'), md5(uniqid('', true)));
|
2021-12-07 22:14:12 -08:00
|
|
|
}
|
|
|
|
|
|
2021-04-12 18:36:34 -07:00
|
|
|
/**
|
|
|
|
|
* Check if token in session matches current token.
|
|
|
|
|
*
|
2021-10-29 22:09:38 -07:00
|
|
|
* @param string|null $token Contains the form token which will be checked against the session variable.
|
|
|
|
|
*
|
|
|
|
|
* @throws Exception
|
2024-03-09 03:19:55 -08:00
|
|
|
* @return bool Whether token matches.
|
2021-04-12 18:36:34 -07:00
|
|
|
*/
|
2025-03-29 10:50:03 +00:00
|
|
|
public static function check(?string $token = null): bool
|
2024-03-09 03:19:55 -08:00
|
|
|
{
|
2022-07-03 20:56:15 +02:00
|
|
|
if ($token === null) {
|
2021-04-06 19:21:49 -07:00
|
|
|
$token = Input::get('token');
|
|
|
|
|
}
|
2021-12-07 22:14:12 -08:00
|
|
|
|
2022-06-12 20:35:45 -06:00
|
|
|
$tokenName = Config::get('session.token_name');
|
2020-12-13 19:38:04 +01:00
|
|
|
|
|
|
|
|
// Check the token matches
|
2020-12-13 20:42:04 -08:00
|
|
|
return Session::exists($tokenName) && $token === Session::get($tokenName);
|
2020-12-13 19:38:04 +01:00
|
|
|
}
|
|
|
|
|
}
|