1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace kalanis\kw_forms\Controls\Security\Csrf; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
use ArrayAccess; |
7
|
|
|
use kalanis\kw_forms\Interfaces\ICsrf; |
8
|
|
|
|
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class Simple2 |
12
|
|
|
* Secure forms by simple tokens |
13
|
|
|
* @package kalanis\kw_forms\Controls\Security\Csrf |
14
|
|
|
*/ |
15
|
|
|
class Simple2 implements ICsrf |
16
|
|
|
{ |
17
|
|
|
protected ?ArrayAccess $session = null; |
18
|
|
|
protected int $expire = 3600; |
19
|
|
|
|
20
|
1 |
|
public function init(ArrayAccess &$cookie, int $expire = 3600): void |
21
|
|
|
{ |
22
|
1 |
|
$this->session = $cookie; |
23
|
1 |
|
$this->expire = $expire; |
24
|
1 |
|
} |
25
|
|
|
|
26
|
1 |
|
public function removeToken(string $codeName): void |
27
|
|
|
{ |
28
|
1 |
|
if ($this->getSession()->offsetExists($codeName)) { |
29
|
1 |
|
$this->getSession()->offsetUnset($codeName); |
30
|
|
|
} |
31
|
1 |
|
} |
32
|
|
|
|
33
|
1 |
|
public function getToken(string $codeName): string |
34
|
|
|
{ |
35
|
1 |
|
if (!$this->getSession()->offsetExists($codeName)) { |
36
|
1 |
|
$this->getSession()->offsetSet($codeName, bin2hex(random_bytes(64))); |
37
|
1 |
|
$this->getSession()->offsetSet($codeName . '_timer', time() + $this->expire); |
38
|
|
|
} |
39
|
1 |
|
return strval($this->getSession()->offsetGet($codeName)); |
40
|
|
|
} |
41
|
|
|
|
42
|
1 |
|
public function getExpire(): int |
43
|
|
|
{ |
44
|
1 |
|
return $this->expire; |
45
|
|
|
} |
46
|
|
|
|
47
|
1 |
|
public function checkToken(string $token, string $codeName): bool |
48
|
|
|
{ |
49
|
1 |
|
return $this->getSession()->offsetExists($codeName) |
50
|
1 |
|
&& $this->getSession()->offsetExists($codeName . '_timer') |
51
|
1 |
|
&& $this->getSession()->offsetGet($codeName) == $token |
52
|
1 |
|
&& $this->getSession()->offsetGet($codeName . '_timer') > time() |
53
|
|
|
; |
54
|
|
|
} |
55
|
|
|
|
56
|
1 |
|
protected function getSession(): ArrayAccess |
57
|
|
|
{ |
58
|
1 |
|
if (!empty($this->session)) { |
59
|
1 |
|
return $this->session; |
60
|
|
|
} |
61
|
|
|
// @codeCoverageIgnoreStart |
62
|
|
|
// you need to whant session before call that sets the control |
63
|
|
|
throw new \LogicException('Set the session first!'); |
64
|
|
|
// @codeCoverageIgnoreEnd |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|