diff options
| author | Thomas Vanbesien <tvanbesi@proton.me> | 2026-03-21 21:35:51 +0100 |
|---|---|---|
| committer | Thomas Vanbesien <tvanbesi@proton.me> | 2026-03-21 21:35:51 +0100 |
| commit | bc54c8c31e7f50a7a365f9b4d22fe8c74a29f61a (patch) | |
| tree | 73a88384b9e472386d244119a0b4e4aa028c8b32 /src/app/Csrf.php | |
| parent | d1ef15fa39935bfa0420c5ac2b8c269e294c9a6d (diff) | |
| download | camagru-bc54c8c31e7f50a7a365f9b4d22fe8c74a29f61a.tar.gz camagru-bc54c8c31e7f50a7a365f9b4d22fe8c74a29f61a.zip | |
Add user authentication with email verification and password reset
Implements registration, login/logout, email verification via token,
and password reset flow. Includes CSRF protection, flash messages,
MailPit for dev email testing, and security docs in README.
Diffstat (limited to 'src/app/Csrf.php')
| -rw-r--r-- | src/app/Csrf.php | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/src/app/Csrf.php b/src/app/Csrf.php new file mode 100644 index 0000000..a18c5d9 --- /dev/null +++ b/src/app/Csrf.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); +// CSRF token generation and validation. +// Prevents attackers from tricking logged-in users into submitting unwanted requests. +// See README.md for a full explanation of the CSRF attack and how tokens prevent it. + +namespace App; + +class Csrf +{ + public static function generate(): string + { + // Reuse the token for the whole session so multiple tabs/forms work + if (empty($_SESSION['csrf_token'])) { + $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); + } + return $_SESSION['csrf_token']; + } + + public static function validate(string $token): bool + { + // hash_equals() prevents timing attacks (constant-time comparison) + return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token); + } + + public static function field(): string + { + // Returns a hidden <input> to embed in HTML forms + $token = htmlspecialchars(self::generate()); + return '<input type="hidden" name="csrf_token" value="' . $token . '">'; + } +} |
