about summary refs log tree commit diff stats
path: root/classes/CsrfMiddleware.php
diff options
context:
space:
mode:
Diffstat (limited to 'classes/CsrfMiddleware.php')
-rw-r--r--classes/CsrfMiddleware.php30
1 files changed, 30 insertions, 0 deletions
diff --git a/classes/CsrfMiddleware.php b/classes/CsrfMiddleware.php
new file mode 100644
index 0000000..8510766
--- /dev/null
+++ b/classes/CsrfMiddleware.php
@@ -0,0 +1,30 @@
+<?php
+
+class CsrfMiddleware implements MiddlewareInterface
+{
+    /** @var array<string> */
+    private array $csrfIgnore = [
+        "cover", "download", "getpagination", "getlastread"
+    ];
+
+    public function process(Request $request, callable $next): Response
+    {
+        if (empty($_SESSION['owner'])) {
+            return $next($request);
+        }
+
+        $op = $request->getAttribute('op');
+
+        $csrfToken = $request->getAttribute('csrf_token', '');
+
+        if (!in_array($op, $this->csrfIgnore) && !validate_csrf($csrfToken)) {
+            $response = (new Response())
+                ->withStatus(401)
+                ->withBody("Unauthorized (CSRF)");
+            $response->send();
+            exit;
+        }
+
+        return $next($request);
+    }
+}