Total Complexity | 13 |
Total Lines | 58 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 0 |
1 | <?php |
||
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 |
|
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 |
|
66 | } |
||
67 | } |
||
68 |