Csrf   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 13
eloc 22
dl 0
loc 58
ccs 25
cts 25
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 5 1
A __construct() 0 7 2
A set() 0 8 2
B verify() 0 29 8
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