1 | <?php |
||
14 | class Csrf |
||
15 | { |
||
16 | use Utils\FormTrait; |
||
17 | use Utils\StorageTrait; |
||
18 | |||
19 | const KEY = 'CSRF'; |
||
20 | const KEY_GENERATOR = 'CSRF_GENERATOR'; |
||
21 | |||
22 | /** |
||
23 | * @var int Max number of CSRF tokens |
||
24 | */ |
||
25 | private $maxTokens = 100; |
||
26 | |||
27 | /** |
||
28 | * @var string field name with the CSRF index |
||
29 | */ |
||
30 | private $formIndex = '_CSRF_INDEX'; |
||
31 | |||
32 | /** |
||
33 | * @var string field name with the CSRF token |
||
34 | */ |
||
35 | private $formToken = '_CSRF_TOKEN'; |
||
36 | |||
37 | /** |
||
38 | * Returns a callable to generate the inputs. |
||
39 | * |
||
40 | * @param ServerRequestInterface $request |
||
41 | * |
||
42 | * @return callable|null |
||
43 | */ |
||
44 | public static function getGenerator(ServerRequestInterface $request) |
||
48 | |||
49 | /** |
||
50 | * Execute the middleware. |
||
51 | * |
||
52 | * @param ServerRequestInterface $request |
||
53 | * @param ResponseInterface $response |
||
54 | * @param callable $next |
||
55 | * |
||
56 | * @return ResponseInterface |
||
57 | */ |
||
58 | public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
||
96 | |||
97 | /** |
||
98 | * Generate and retrieve the tokens. |
||
99 | * |
||
100 | * @param ServerRequestInterface $request |
||
101 | * @param string $lockTo |
||
102 | * @param array $tokens |
||
103 | * |
||
104 | * @return string |
||
105 | */ |
||
106 | private function generateTokens(ServerRequestInterface $request, $lockTo, array &$tokens) |
||
126 | |||
127 | /** |
||
128 | * Validate the request. |
||
129 | * |
||
130 | * @param ServerRequestInterface $request |
||
131 | * @param array &$tokens |
||
132 | * |
||
133 | * @return bool |
||
134 | */ |
||
135 | private function validateRequest(ServerRequestInterface $request, array &$tokens) |
||
163 | |||
164 | /** |
||
165 | * Encode string with base64, but strip padding. |
||
166 | * PHP base64_decode does not croak on that. |
||
167 | * |
||
168 | * @param string $value |
||
169 | * |
||
170 | * @return string |
||
171 | */ |
||
172 | private static function encode($value) |
||
176 | |||
177 | /** |
||
178 | * Return a random token. |
||
179 | * |
||
180 | * @param int $length The length of the random string that should be returned in bytes. |
||
181 | * |
||
182 | * @return string |
||
183 | */ |
||
184 | private function randomToken($length = 32) |
||
200 | } |
||
201 |