From d549cf914f6a833516ca7d2160e251b1c3afbf5a Mon Sep 17 00:00:00 2001 From: Yisroel Baum Date: Fri, 24 Apr 2026 13:25:36 +0300 Subject: [PATCH] add auth middleware --- app/Auth/AuthMiddleware.php | 84 +++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 app/Auth/AuthMiddleware.php diff --git a/app/Auth/AuthMiddleware.php b/app/Auth/AuthMiddleware.php new file mode 100644 index 0000000..e72fba8 --- /dev/null +++ b/app/Auth/AuthMiddleware.php @@ -0,0 +1,84 @@ +getCookieParams(); + $token = $cookies[self::COOKIE_NAME] ?? null; + + if ($token === null) { + return $this->unauthorized($request); + } + + $session = $this->sessionRepo->findByToken($token); + if ($session === null) { + return $this->unauthorized($request); + } + + if ($session->isExpired($this->clock->now())) { + $this->sessionRepo->deleteByToken($token); + return $this->unauthorized($request); + } + + $user = $this->userRepo->find($session->getUserId()); + if ($user === null) { + return $this->unauthorized($request); + } + + return $handler->handle( + $request->withAttribute('user', $user) + ); + } + + private function unauthorized( + ServerRequestInterface $request + ): ResponseInterface { + if ($this->wantsJson($request)) { + $response = new Response(401); + $response->getBody()->write( + json_encode(['error' => 'unauthenticated']) + ); + return $response->withHeader( + 'Content-Type', + 'application/json' + ); + } + + return new Response(302)->withHeader('Location', '/login'); + } + + 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; + } +}