@@ 1,40 0,0 @@
-<?php
-declare(strict_types=1);
-
-namespace Thirdplace;
-
-final class CsrfMiddleware
-{
- public function __invoke(Request $request): Request
- {
- if ($request->isPost()) {
- $tokenFromRequest = $request->post('csrf', [], true);
-
- if (!$tokenFromRequest) {
- throw new \Exception('Missing token from request');
- }
- if (!isset($tokenFromRequest['key'])) {
- throw new \Exception('Missing token key from request');
- }
-
- $tokenFromSession = $_SESSION['thirdplace'][$tokenFromRequest['key']] ?? null;
-
- if (!$tokenFromSession) {
- throw new \Exception('Unknown token key');
- }
-
- if (! hash_equals($tokenFromRequest['value'], $tokenFromSession['value'])) {
- throw new \Exception('Token mismatch');
- }
- }
-
- $token = [
- 'key' => sprintf('csrf_key_%s', bin2hex(random_bytes(16))),
- 'value' => sprintf('csrf_value_%s', bin2hex(random_bytes(16))),
- ];
-
- $_SESSION['thirdplace'][$token['key']] = $token;
-
- return $request->withAttribute('csrf', $token);
- }
-}>
\ No newline at end of file