1 | <?php |
||
16 | class Csrf |
||
17 | { |
||
18 | use Utils\FormTrait; |
||
19 | |||
20 | /** |
||
21 | * @var int Max number of CSRF tokens |
||
22 | */ |
||
23 | private $maxTokens = 100; |
||
24 | |||
25 | /** |
||
26 | * @var string field name with the CSRF index |
||
27 | */ |
||
28 | private $formIndex = '_CSRF_INDEX'; |
||
29 | |||
30 | /** |
||
31 | * @var string field name with the CSRF token |
||
32 | */ |
||
33 | private $formToken = '_CSRF_TOKEN'; |
||
34 | |||
35 | /* |
||
36 | * @var array|ArrayAccess CSRF storage |
||
37 | */ |
||
38 | private $storage; |
||
39 | |||
40 | /** |
||
41 | * @var string Index used in the storage |
||
42 | */ |
||
43 | private $sessionIndex = 'CSRF'; |
||
44 | |||
45 | /** |
||
46 | * Set the storage of the CSRF |
||
47 | * |
||
48 | * @param array|ArrayAccess|null $storage |
||
49 | */ |
||
50 | public function __construct(&$storage = null) |
||
60 | |||
61 | /** |
||
62 | * Execute the middleware. |
||
63 | * |
||
64 | * @param ServerRequestInterface $request |
||
65 | * @param ResponseInterface $response |
||
66 | * @param callable $next |
||
67 | * |
||
68 | * @return ResponseInterface |
||
69 | */ |
||
70 | public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
||
110 | |||
111 | /** |
||
112 | * Generate and retrieve the tokens. |
||
113 | * |
||
114 | * @param ServerRequestInterface $request |
||
115 | * @param string $lockTo |
||
116 | * |
||
117 | * @return array |
||
118 | */ |
||
119 | private function generateTokens(ServerRequestInterface $request, $lockTo) |
||
138 | |||
139 | /** |
||
140 | * Validate the request. |
||
141 | * |
||
142 | * @param ServerRequestInterface $request |
||
143 | * |
||
144 | * @return bool |
||
145 | */ |
||
146 | private function validateRequest(ServerRequestInterface $request) |
||
174 | |||
175 | /** |
||
176 | * Enforce an upper limit on the number of tokens stored in session state |
||
177 | * by removing the oldest tokens first. |
||
178 | */ |
||
179 | private function recycleTokens() |
||
193 | |||
194 | /** |
||
195 | * Encode string with base64, but strip padding. |
||
196 | * PHP base64_decode does not croak on that. |
||
197 | * |
||
198 | * @param string $value |
||
199 | * |
||
200 | * @return string |
||
201 | */ |
||
202 | private static function encode($value) |
||
206 | } |
||
207 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: