|
8 | 8 | ----- |
9 | 9 | """ |
10 | 10 |
|
| 11 | +import os |
11 | 12 | from fastapi import Request |
12 | 13 | from fastapi.responses import JSONResponse |
13 | 14 | from starlette.middleware.base import BaseHTTPMiddleware |
14 | 15 | from starlette import status |
15 | 16 |
|
16 | | -from src.config import config |
| 17 | +from src.services.kg_agent.main import cache_adapter |
| 18 | +from src.services.data.main import data_adapter |
17 | 19 |
|
18 | 20 |
|
19 | 21 | class BrainPATMiddleware(BaseHTTPMiddleware): |
20 | 22 | async def dispatch(self, request: Request, call_next): |
21 | 23 | if request.method == "OPTIONS": |
22 | 24 | return await call_next(request) |
23 | | - brainpat = request.headers.get("BrainPAT") |
24 | | - if brainpat != config.brainpat_token: |
| 25 | + |
| 26 | + brainpat = request.headers.get("BrainPAT") or getattr( |
| 27 | + request.state, "pat", None |
| 28 | + ) |
| 29 | + brain_id = getattr(request.state, "brain_id", None) |
| 30 | + |
| 31 | + cachepat_key = f"brainpat:{brain_id or 'default'}" |
| 32 | + |
| 33 | + use_only_system_pat = os.getenv("USE_ONLY_SYSTEM_PAT") == "true" |
| 34 | + |
| 35 | + if use_only_system_pat: |
| 36 | + cachepat_key = "brainpat:system" |
| 37 | + |
| 38 | + cached_brainpat = cache_adapter.get(key=cachepat_key, brain_id="system") |
| 39 | + |
| 40 | + if not cached_brainpat and not use_only_system_pat: |
| 41 | + stored_brain = data_adapter.get_brain(name_key=brain_id) |
| 42 | + system_pat = os.getenv("BRAINPAT_TOKEN") |
| 43 | + if not stored_brain and brainpat != system_pat: |
| 44 | + return JSONResponse( |
| 45 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 46 | + content={"detail": "Invalid or missing BrainPAT header"}, |
| 47 | + ) |
| 48 | + |
| 49 | + cached_brainpat = stored_brain.pat |
| 50 | + cache_adapter.set( |
| 51 | + key=cachepat_key, |
| 52 | + value=stored_brain.pat, |
| 53 | + brain_id="system", |
| 54 | + ) |
| 55 | + if not cached_brainpat and use_only_system_pat: |
| 56 | + system_pat = os.getenv("BRAINPAT_TOKEN") |
| 57 | + cached_brainpat = system_pat |
| 58 | + cache_adapter.set( |
| 59 | + key="brainpat:system", |
| 60 | + value=system_pat, |
| 61 | + brain_id="system", |
| 62 | + ) |
| 63 | + |
| 64 | + if cached_brainpat != brainpat: |
25 | 65 | return JSONResponse( |
26 | 66 | status_code=status.HTTP_401_UNAUTHORIZED, |
27 | 67 | content={"detail": "Invalid or missing BrainPAT header"}, |
28 | 68 | ) |
29 | 69 | response = await call_next(request) |
| 70 | + |
30 | 71 | return response |
0 commit comments