You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.3 KiB
87 lines
2.3 KiB
<?php
|
|
|
|
declare(strict_types=1);
|
|
namespace tts\traits\security;
|
|
|
|
trait csrf_token_functions {
|
|
|
|
/**
|
|
* Get an Cross-Site Request Forge - Prevention Token
|
|
* @return string
|
|
*/
|
|
public static function csrf_token(): string {
|
|
return self::get_unique_id();
|
|
}
|
|
|
|
/**
|
|
* Set Session to use CSRF Token
|
|
* @return string CSRF Token
|
|
*/
|
|
public static function create_csrf_token(): string {
|
|
$token = self::csrf_token();
|
|
$_SESSION['csrf_token'] = $token;
|
|
$_SESSION['csrf_token_time'] = time();
|
|
return $token;
|
|
}
|
|
|
|
/**
|
|
* Destroy CSRF Token from Session
|
|
* @return bool success
|
|
*/
|
|
public static function destroy_csrf_token(): bool {
|
|
$_SESSION['csrf_token'] = null;
|
|
$_SESSION['csrf_token_time'] = null;
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Get CSRF Token for use with HTML Form
|
|
* @return string Hidden Form with token set
|
|
*/
|
|
public static function csrf_token_tag(): string {
|
|
$token = self::create_csrf_token();
|
|
return "<input type=\"hidden\" name=\"csrf_token\" value=\"" . $token . "\">";
|
|
}
|
|
|
|
/**
|
|
* Check if POST data CSRF Token is Valid
|
|
* @return bool is valid
|
|
*/
|
|
public static function csrf_token_is_valid(): bool {
|
|
$is_csrf = filter_has_var(INPUT_POST, 'csrf_token');
|
|
if ($is_csrf) {
|
|
$user_token = \tts\request::post_var('csrf_token');
|
|
$stored_token = $_SESSION['csrf_token'] ?? '';
|
|
if (empty($stored_token)) {
|
|
return false;
|
|
}
|
|
return \tts\request::compair_it($user_token, $stored_token);
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Optional check to see if token is also recent
|
|
* @return bool
|
|
*/
|
|
public static function csrf_token_is_recent(): bool {
|
|
$max_elapsed = intval(\main_tts\configure::get(
|
|
'security',
|
|
'max_token_age'
|
|
));
|
|
if ($max_elapsed < 30) {
|
|
$max_elapsed = 60 * 60 * 24; // 1 day
|
|
}
|
|
|
|
if (isset($_SESSION['csrf_token_time'])) {
|
|
$stored_time = $_SESSION['csrf_token_time'];
|
|
return ($stored_time + $max_elapsed) >= time();
|
|
} else {
|
|
// Remove expired token
|
|
self::destroy_csrf_token();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
}
|
|
|