From bb4e27a45bfd10e0a2e9d8cc0aeed1fb13f0a781 Mon Sep 17 00:00:00 2001 From: Yisroel Baum Date: Fri, 24 Apr 2026 13:26:38 +0300 Subject: [PATCH] add admin middleware --- app/Auth/AdminMiddleware.php | 64 ++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 app/Auth/AdminMiddleware.php diff --git a/app/Auth/AdminMiddleware.php b/app/Auth/AdminMiddleware.php new file mode 100644 index 0000000..47e16be --- /dev/null +++ b/app/Auth/AdminMiddleware.php @@ -0,0 +1,64 @@ +getAttribute('user'); + + if (!$user instanceof User || !$user->isAdmin()) { + return $this->forbidden($request); + } + + return $handler->handle($request); + } + + private function forbidden( + ServerRequestInterface $request + ): ResponseInterface { + $response = new Response(403); + + if ($this->wantsJson($request)) { + $response->getBody()->write( + json_encode(['error' => 'forbidden']) + ); + return $response->withHeader( + 'Content-Type', + 'application/json' + ); + } + + $html = file_get_contents( + __DIR__ . '/../../views/templates/forbidden.php' + ); + $response->getBody()->write($html); + + return $response->withHeader('Content-Type', 'text/html'); + } + + private function wantsJson(ServerRequestInterface $request): bool + { + $path = $request->getUri()->getPath(); + if (str_starts_with($path, '/api/')) { + return true; + } + + $accept = $request->getHeaderLine('Accept'); + if (str_contains($accept, 'application/json')) { + return true; + } + + return false; + } +}