1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace kalanis\kw_forms\Controls\Security; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
use ArrayAccess; |
7
|
|
|
use kalanis\kw_forms\Controls\Hidden; |
8
|
|
|
use kalanis\kw_forms\Interfaces\ICsrf; |
9
|
|
|
use kalanis\kw_rules\Interfaces\IRules; |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class Csrf |
14
|
|
|
* @package kalanis\kw_forms\Controls\Security |
15
|
|
|
* Hidden entry which adds CSRF check |
16
|
|
|
* Must be child of hidden due necessity of pre-setting position in render |
17
|
|
|
* This one set another value to compare, on the other way multisend sets nothing |
18
|
|
|
*/ |
19
|
|
|
class Csrf extends Hidden |
20
|
|
|
{ |
21
|
|
|
/** @var ICsrf */ |
22
|
|
|
protected $csrf = null; |
23
|
|
|
/** @var string */ |
24
|
|
|
protected $csrfTokenAlias = ''; |
25
|
|
|
|
26
|
2 |
|
public function __construct() |
27
|
|
|
{ |
28
|
2 |
|
$this->csrf = $this->getCsrfLib(); |
29
|
2 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @return ICsrf |
33
|
|
|
* @codeCoverageIgnore link adapter remote resource |
34
|
|
|
*/ |
35
|
1 |
|
protected function getCsrfLib(): ICsrf |
36
|
|
|
{ |
37
|
1 |
|
return new Csrf\JWT(); |
38
|
|
|
} |
39
|
|
|
|
40
|
1 |
|
public function setHidden(string $alias, ArrayAccess &$cookie, string $errorMessage): self |
41
|
|
|
{ |
42
|
1 |
|
$this->csrf->init($cookie); |
43
|
1 |
|
$this->setEntry($alias); |
44
|
1 |
|
$this->csrfTokenAlias = "{$alias}SubmitCheck"; |
45
|
1 |
|
$this->setValue($this->csrf->getToken($this->csrfTokenAlias)); |
46
|
1 |
|
parent::addRule(IRules::SATISFIES_CALLBACK, $errorMessage, [$this, 'checkToken']); |
47
|
1 |
|
return $this; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param mixed $incomingValue |
52
|
|
|
* @return bool |
53
|
|
|
*/ |
54
|
1 |
|
public function checkToken($incomingValue): bool |
55
|
|
|
{ |
56
|
1 |
|
if ($this->csrf->checkToken(strval($incomingValue), $this->csrfTokenAlias)) { |
57
|
|
|
// token reload |
58
|
1 |
|
$this->csrf->removeToken($this->csrfTokenAlias); |
59
|
1 |
|
$this->setValue($this->csrf->getToken($this->csrfTokenAlias)); |
60
|
1 |
|
return true; |
61
|
|
|
} else { |
62
|
1 |
|
return false; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
1 |
|
public function addRule(/** @scrutinizer ignore-unused */ string $ruleName, /** @scrutinizer ignore-unused */ string $errorText, /** @scrutinizer ignore-unused */ ...$args): void |
67
|
|
|
{ |
68
|
|
|
// no additional rules applicable |
69
|
1 |
|
} |
70
|
|
|
|
71
|
1 |
|
public function addRules(/** @scrutinizer ignore-unused */ iterable $rules = []): void |
72
|
|
|
{ |
73
|
|
|
// no rules add applicable |
74
|
1 |
|
} |
75
|
|
|
|
76
|
1 |
|
public function removeRules(): void |
77
|
|
|
{ |
78
|
|
|
// no rules removal applicable |
79
|
1 |
|
} |
80
|
|
|
|
81
|
1 |
|
public function renderErrors($errors): string |
82
|
|
|
{ |
83
|
1 |
|
return ''; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|