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; } }