phase0-multi-tenant-rls-rbac

This commit is contained in:
QihuAI Design committed 2026-07-27 09:44:06 +08:00
1 parent f9c8bda6e0
commit 7b1941fdaf
3 files changed
+97 -2

No files matched your search

+27
View File
@@ -11,6 +11,30 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.base import BaseHTTPMiddleware
# Phase0: Tenant RLS Middleware
class TenantRLSMiddleware(BaseHTTPMiddleware):
"""Inject tenant_id from JWT into PostgreSQL for RLS policies"""
async def dispatch(self, request: Request, call_next):
try:
auth_header = request.headers.get("Authorization", "")
if auth_header.startswith("Bearer "):
from jose import jwt
from app.auth import SECRET_KEY, ALGORITHM
token = auth_header[7:]
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
tenant_id = payload.get("tenant_id")
if tenant_id:
from app.database import SessionLocal
db = SessionLocal()
try:
db.execute(f"SET app.current_tenant = '{tenant_id}'")
finally:
db.close()
except Exception:
pass
return await call_next(request)
from datetime import datetime
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -206,6 +230,9 @@ app.add_middleware(
)
# 前台 API
# Phase0: Register RLS middleware
app.add_middleware(TenantRLSMiddleware)
app.include_router(auth.router, prefix="/app/api/auth", tags=["认证"])
app.include_router(chat.router, prefix="/app/api/chat", tags=["AI聊天"])
app.include_router(knowledge.router, prefix="/app/api/knowledge", tags=["知识库"])