aboutsummaryrefslogtreecommitdiffstats
path: root/src/app/Csrf.php
blob: a18c5d91c5a2c9c2116bb6f0e87c140714f4a9c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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 . '">';
    }
}