Csrf::get()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Conia\Session;
6
7
/** @psalm-api */
8
class Csrf
9
{
10 6
    public function __construct(
11
        protected string $sessionKey = 'csrftokens',
12
        protected string $postKey = 'csrftoken',
13
        protected string $headerKey = 'HTTP_X_CSRF_TOKEN',
14
    ) {
15 6
        if (!isset($_SESSION[$this->sessionKey])) {
16 5
            $_SESSION[$this->sessionKey] = [];
17
        }
18
    }
19
20 5
    public function get(string $page = 'default'): string
21
    {
22 5
        $token = (string)($_SESSION[$this->sessionKey][$page] ?? $this->set($page));
23
24 5
        return $token;
25
    }
26
27 5
    public function verify(
28
        string $page = 'default',
29
        string $token = null
30
    ): bool {
31 5
        if ($token === null) {
32 5
            $token = $_POST[$this->postKey] ?? null;
33
        }
34
35 5
        if ($token === null) {
36 3
            if (isset($_SERVER[$this->headerKey])) {
37 2
                $token = $_SERVER[$this->headerKey];
38
            }
39
        }
40
41 5
        if ($token === null) {
42 1
            return false;
43
        }
44
45 4
        $savedToken = $this->get($page);
46
47 4
        if (empty($savedToken)) {
48 1
            return false;
49
        }
50
51 3
        if (is_string($token) && !empty($token)) {
52 3
            return hash_equals($savedToken, $token);
53
        }
54
55 1
        return false;
56
    }
57
58 5
    protected function set(string $page = 'default'): string
59
    {
60 5
        assert(isset($_SESSION[$this->sessionKey]) && is_array($_SESSION[$this->sessionKey]));
61
62 5
        $token = base64_encode(random_bytes(32));
63 5
        $_SESSION[$this->sessionKey][$page] = $token;
64
65 5
        return $token;
66
    }
67
}
68