|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* CSRF token |
|
4
|
|
|
* |
|
5
|
|
|
* PHP version 5.5 |
|
6
|
|
|
* |
|
7
|
|
|
* @category OpCacheGUI |
|
8
|
|
|
* @package Security |
|
9
|
|
|
* @author Pieter Hordijk <[email protected]> |
|
10
|
|
|
* @copyright Copyright (c) 2013 Pieter Hordijk <https://github.com/PeeHaa> |
|
11
|
|
|
* @license http://www.opensource.org/licenses/mit-license.html MIT License |
|
12
|
|
|
* @version 1.0.0 |
|
13
|
|
|
*/ |
|
14
|
|
|
namespace OpCacheGUI\Security; |
|
15
|
|
|
|
|
16
|
|
|
use OpCacheGUI\Storage\KeyValuePair; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* CSRF token |
|
20
|
|
|
* |
|
21
|
|
|
* @category OpCacheGUI |
|
22
|
|
|
* @package Security |
|
23
|
|
|
* @author Pieter Hordijk <[email protected]> |
|
24
|
|
|
*/ |
|
25
|
|
|
class CsrfToken |
|
26
|
|
|
{ |
|
27
|
|
|
/** |
|
28
|
|
|
* The length of the tokens |
|
29
|
|
|
*/ |
|
30
|
|
|
const LENGTH = 56; |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* @var \OpCacheGUI\Storage\keyValuePair Instance of a key value storage |
|
34
|
|
|
*/ |
|
35
|
|
|
private $storage; |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* Creates instance |
|
39
|
|
|
* |
|
40
|
|
|
* @param \OpCacheGUI\Storage\KeyValuePair $storage Instance of a key value storage |
|
41
|
|
|
*/ |
|
42
|
4 |
|
public function __construct(KeyValuePair $storage) |
|
43
|
|
|
{ |
|
44
|
4 |
|
$this->storage = $storage; |
|
45
|
4 |
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Gets the stored CSRF token |
|
49
|
|
|
* |
|
50
|
|
|
* @return string The stored CSRF token |
|
51
|
|
|
*/ |
|
52
|
4 |
|
public function get() |
|
53
|
|
|
{ |
|
54
|
4 |
|
if (!$this->storage->isKeyValid('csrfToken')) { |
|
55
|
1 |
|
$this->storage->set('csrfToken', $this->generate()); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
4 |
|
return $this->storage->get('csrfToken'); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Validates the supplied token against the stored token |
|
63
|
|
|
* |
|
64
|
|
|
* @param string $token The token to validate |
|
65
|
|
|
* |
|
66
|
|
|
* @return boolean True when the supplied token matches the stored token |
|
67
|
|
|
*/ |
|
68
|
2 |
|
public function validate($token) |
|
69
|
|
|
{ |
|
70
|
2 |
|
return $token === $this->get(); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* Generates a new secure CSRF token |
|
75
|
|
|
* |
|
76
|
|
|
* @return string The generated CSRF token |
|
77
|
|
|
* @throws InsufficientRandomData |
|
78
|
|
|
*/ |
|
79
|
1 |
|
private function generate() |
|
80
|
|
|
{ |
|
81
|
|
|
try { |
|
82
|
1 |
|
$token = random_bytes(self::LENGTH); |
|
83
|
|
|
} catch (\Throwable $e) { |
|
84
|
|
|
throw new InsufficientRandomData($e->getMessage(), $e->getCode(), $e); |
|
85
|
|
|
} |
|
86
|
|
|
|
|
87
|
1 |
|
return bin2hex($token); |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
|