mc-cms-namelessmc/core/classes/Core/Token.php

62 lines
1.4 KiB
PHP
Raw Permalink Normal View History

<?php
/**
* Validates and generates CSRF tokens.
*
* @package NamelessMC\Core
* @author Samerton
* @version 2.0.0-pr8
* @license MIT
*/
class Token
{
/**
* Get current form token.
*
* @return string current form token.
*/
public static function get(): string
{
$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
// 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
/**
* Generate a form token and store in a session variable.
2021-12-07 22:14:12 -08:00
*/
public static function generate(): void
{
2021-12-07 22:14:12 -08:00
// Generate random token using md5
Session::put(Config::get('session.token_name'), md5(uniqid('', true)));
2021-12-07 22:14:12 -08: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
* @return bool Whether token matches.
*/
public static function check(?string $token = null): bool
{
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
$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
}
}