Skip to content

Commit f6f30a3

Browse files
"Added CSRF token class because apparently we can't trust our users to not submit duplicate forms."
1 parent 1556915 commit f6f30a3

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<?php
2+
/*
3+
* Spindle CMS
4+
* Copyright (c) 2025. All rights reserved.
5+
*
6+
* This file is part of the Spindle CMS project — a lightweight, modular PHP content framework derived from OpenCart.
7+
*
8+
* @license GNU General Public License v3.0 (GPL-3.0-or-later)
9+
* @link https://github.com/RandomCoderTinker/Spindle
10+
*/
11+
12+
namespace Spindle\System\Library\Security;
13+
14+
class Csrf
15+
{
16+
private string $token;
17+
private Session $session;
18+
19+
/**
20+
* CSRF constructor using custom session system (e.g., RedisHandler)
21+
*
22+
* @param Session $session
23+
*/
24+
public function __construct (Session $session)
25+
{
26+
$this->session = $session;
27+
28+
if (empty($this->session->get('csrf_token'))) {
29+
$this->regenerateToken();
30+
} else {
31+
$this->token = $this->session->get('csrf_token');
32+
}
33+
}
34+
35+
/**
36+
* Get the current CSRF token
37+
*
38+
* @return string
39+
*/
40+
public function getCsrfToken (): string
41+
{
42+
return $this->token;
43+
}
44+
45+
/**
46+
* Validate a given CSRF token against the session token
47+
*
48+
* @param string $csrf
49+
*
50+
* @return bool
51+
*/
52+
public function checkToken (string $csrf): bool
53+
{
54+
return hash_equals($this->token, $csrf);
55+
}
56+
57+
/**
58+
* Regenerate the CSRF token
59+
*
60+
* Call this method after a successful form submission
61+
*
62+
* @return void
63+
*/
64+
public function regenerateToken (): void
65+
{
66+
$this->session->lazySet('csrf_token', spindle_token(32));
67+
}
68+
69+
}

0 commit comments

Comments
 (0)