about summary refs log tree commit diff stats
path: root/classes/CsrfMiddleware.php
blob: 1a49d48b598fcfa1215933ed4dd75f87b386e626 (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->getAttribute('op');

		$csrfToken = $request->getAttribute('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);
	}
}