about summary refs log tree commit diff stats
path: root/classes/CsrfMiddleware.php
blob: 5edf4e413f84713b7937691c1513da2419ae4f75 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php

class CsrfMiddleware implements MiddlewareInterface
{
    /** @var array<string> */
    private array $csrfIgnore = [
        "cover", "download", "getpagination", "getlastread", "getinfo", "list", "healthz"
    ];

    public function process(Request $request, callable $next): Response
    {
        if (empty($_SESSION['owner'])) {
            return $next($request);
        }

        $op = $request->getString('op');

        $csrfToken = $request->fromBody()->getString('csrf_token', '');

        if (!in_array($op, $this->csrfIgnore) && !validate_csrf($csrfToken)) {
            $response = (new Response())
                ->withStatus(401)
                ->withBody(json_encode(["error" => "Unauthorized (CSRF)"]));
            $response->send();
            exit;
        }

        return $next($request);
    }
}