This repository has been archived on 2024-06-26. You can view files and clone it, but cannot push or open issues or pull requests.
sakura/app/CSRF.php

74 lines
1.4 KiB
PHP
Raw Normal View History

<?php
2016-02-03 23:22:56 +01:00
/**
* Holds the CSRF token handler.
* @package Sakura
*/
namespace Sakura;
/**
2016-02-02 22:04:15 +01:00
* Used to generate and validate CSRF tokens.
* @package Sakura
2016-02-02 22:04:15 +01:00
* @author Julian van de Groep <me@flash.moe>
*/
class CSRF
{
2016-02-02 22:04:15 +01:00
/**
* The prefix to prevent collisions in the $_SESSION variable.
*/
const ID_PREFIX = '_sakura_csrf_';
2016-02-02 22:04:15 +01:00
/**
* The size of the randomly generated string.
*/
const RANDOM_SIZE = 16;
2016-02-02 22:04:15 +01:00
/**
* Create a new CSRF token.
2016-08-05 04:35:37 +02:00
* @param mixed $id
* @return string
2016-02-02 22:04:15 +01:00
*/
public static function create($id)
{
// Generate a token
$token = self::generate();
// Make identifier
$id = strtoupper(self::ID_PREFIX . $id);
// Assign to session
$_SESSION[$id] = $token;
// Return the token
return $token;
}
2016-02-02 22:04:15 +01:00
/**
* Generate a CSRF token.
2016-08-05 04:35:37 +02:00
* @return string
2016-02-02 22:04:15 +01:00
*/
public static function generate()
{
return bin2hex(random_bytes(self::RANDOM_SIZE));
}
2016-02-02 22:04:15 +01:00
/**
* Validate a CSRF token.
2016-08-05 04:35:37 +02:00
* @param string $token
* @param string $id
* @return bool
2016-02-02 22:04:15 +01:00
*/
public static function validate($token, $id)
{
// Set id
$id = strtoupper(self::ID_PREFIX . $id);
// Check if the token exists
if (!array_key_exists($id, $_SESSION)) {
return false;
}
return hash_equals($token, $_SESSION[$id]);
}
}