Spaces:
Sleeping
Sleeping
File size: 1,186 Bytes
9c90775 | 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 | from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
from api.states.user_state import User
class AuthenticateMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
path = request.url.path
# ββ Non-API paths (frontend pages, static assets, favicon) ββββββββββ
# Never block these β anyone can browse the UI freely.
if not path.startswith("/api/v1/"):
return await call_next(request)
# ββ Public API endpoints (no cookie needed) ββββββββββββββββββββββββββ
if path.startswith("/api/v1/user/login"):
return await call_next(request)
# ββ Protected API endpoints β cookie required ββββββββββββββββββββββββ
thread_id = request.cookies.get("thread_id")
if not thread_id:
return JSONResponse({"error": "pls login"}, status_code=401)
request.scope["user"] = User(thread_id=thread_id)
return await call_next(request)
|