Add class MD_STD_SEC for basic security operations
This commit is contained in:
parent
50d3a20b01
commit
aa67de1e54
48
MD_STD_SEC.php
Normal file
48
MD_STD_SEC.php
Normal file
|
@ -0,0 +1,48 @@
|
|||
<?PHP
|
||||
/**
|
||||
* Gathers wrappers for handling basic security operations.
|
||||
*/
|
||||
declare(strict_types = 1);
|
||||
|
||||
/**
|
||||
* Class providing static functions with basic security operations.
|
||||
*/
|
||||
final class MD_STD_SEC {
|
||||
|
||||
/**
|
||||
* Function for retrieving the anti-csrf token or generating it if need be.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function getAntiCsrfToken():string {
|
||||
|
||||
if (empty($_SESSION['csrf-token'])) {
|
||||
$_SESSION['csrf-token'] = bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
return $_SESSION['csrf-token'];
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Function for validating anti-csrf tokens. Each anti-csrf token is removed
|
||||
* after use.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public static function validateAntiCsrfToken():bool {
|
||||
|
||||
$validity = false;
|
||||
if (!empty($_POST['csrf-token'])
|
||||
&& !empty($_SESSION['csrf-token'])
|
||||
&& hash_equals($_SESSION['csrf-token'], $_POST['csrf-token']) === true
|
||||
) {
|
||||
$validity = true;
|
||||
}
|
||||
$_SESSION['csrf-token'] = null; unset($_SESSION['csrf-token']);
|
||||
|
||||
return $validity;
|
||||
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user