From ca8a2066de7da78353d7bc779ef576538d2e8814 Mon Sep 17 00:00:00 2001 From: yisroel Date: Wed, 6 May 2026 15:16:59 +0300 Subject: [PATCH] implement AuthMiddleware reads auth_token cookie (constant COOKIE_NAME for cross-layer sharing with the AuthController). missing/empty cookie or unknown token -> 401 json {error: unauthenticated}. expired session is deleted then 401 returned. valid session attaches the User entity to request attributes under 'user' so downstream controllers can read it via request attributes. 37 tests pass. --- .../app/Http/Middleware/AuthMiddleware.php | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 backend/app/Http/Middleware/AuthMiddleware.php diff --git a/backend/app/Http/Middleware/AuthMiddleware.php b/backend/app/Http/Middleware/AuthMiddleware.php new file mode 100644 index 0000000..8e21ece --- /dev/null +++ b/backend/app/Http/Middleware/AuthMiddleware.php @@ -0,0 +1,51 @@ +cookie(self::COOKIE_NAME); + if (! is_string($token) || $token === '') { + return $this->unauthorized(); + } + + $session = $this->sessionRepo->findByToken($token); + if ($session === null) { + return $this->unauthorized(); + } + + if ($session->isExpired($this->clock->now())) { + $this->sessionRepo->deleteByToken($token); + + return $this->unauthorized(); + } + + $request->attributes->set('user', $session->getUser()); + + return $next($request); + } + + private function unauthorized(): JsonResponse + { + return new JsonResponse(['error' => 'unauthenticated'], 401); + } +}