summaryrefslogtreecommitdiffstats
path: root/app/classes/CSRF.php
blob: cf9fc1e890342dc39adacb3a3fb0f9f628f056cc (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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php

class CSRF
{
    /** @var string */
    const HMAC_ALGORITHM = 'sha256';

    /** @var string */
    const SESSION_KEY_NAME = '_csrf_key';

    /**
     * Ensure that a CSRF token is valid for a given action.
     *
     * @param  string $token
     * @param  string $action
     * @return bool
     */
    public static function verify($token = '', $action = null)
    {
        if (!is_string($token) || !is_string($action)) {
            return false;
        }

        $known = self::generate($action);
        return hash_equals($known, $token);
    }

    /**
     * Generate a CSRF token for a given action.
     *
     * @param  string $action
     * @throws InvalidArgumentException
     * @return string
     */
    public static function generate($action = null)
    {
        if (!is_string($action)) {
            throw new InvalidArgumentException('A valid action must be defined.');
        }
        return hash_hmac(self::HMAC_ALGORITHM, $action, self::getKey());
    }

    /**
     * Get HMAC key.
     *
     * @return string
     */
    public static function getKey()
    {
        if (empty($_SESSION[self::SESSION_KEY_NAME])) {
            $_SESSION[self::SESSION_KEY_NAME] = bin2hex(random_bytes(16));
        }
        return $_SESSION[self::SESSION_KEY_NAME];
    }
}