mirror of
http://88.130.71.182:3000/BlitTech/contexta_be.git
synced 2026-06-12 23:23:21 +00:00
fixed the RAg in test pipeline issue
This commit is contained in:
@@ -1,18 +1,77 @@
|
||||
from fastapi import Depends, HTTPException, status, Header
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from typing import Optional
|
||||
from dataclasses import dataclass, field
|
||||
from app.database import get_supabase
|
||||
from app.config import settings
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
security = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _LocalUser:
|
||||
"""Minimal user object built from JWT claims — mirrors the fields used downstream."""
|
||||
id: str
|
||||
email: str
|
||||
role: str = "authenticated"
|
||||
app_metadata: dict = field(default_factory=dict)
|
||||
user_metadata: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
def _verify_jwt_local(token: str) -> Optional[_LocalUser]:
|
||||
"""Verify a Supabase HS256 JWT using the local secret (no network call).
|
||||
Returns None if the secret is not configured, the signature is wrong, or the token is expired."""
|
||||
secret = settings.supabase_jwt_secret
|
||||
if not secret:
|
||||
return None
|
||||
try:
|
||||
parts = token.split(".")
|
||||
if len(parts) != 3:
|
||||
return None
|
||||
header_b64, payload_b64, sig_b64 = parts
|
||||
|
||||
# Verify HMAC-SHA256 signature
|
||||
message = f"{header_b64}.{payload_b64}".encode()
|
||||
expected = hmac.new(secret.encode(), message, hashlib.sha256).digest()
|
||||
padding = "=" * (-len(sig_b64) % 4)
|
||||
actual = base64.urlsafe_b64decode(sig_b64 + padding)
|
||||
if not hmac.compare_digest(expected, actual):
|
||||
return None
|
||||
|
||||
# Decode payload
|
||||
padding = "=" * (-len(payload_b64) % 4)
|
||||
payload = json.loads(base64.urlsafe_b64decode(payload_b64 + padding))
|
||||
|
||||
# Check expiry
|
||||
if payload.get("exp", 0) < time.time():
|
||||
return None
|
||||
|
||||
return _LocalUser(
|
||||
id=payload["sub"],
|
||||
email=payload.get("email", ""),
|
||||
role=payload.get("role", "authenticated"),
|
||||
app_metadata=payload.get("app_metadata", {}),
|
||||
user_metadata=payload.get("user_metadata", {}),
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
|
||||
):
|
||||
"""Extract and verify the current user from Supabase JWT"""
|
||||
"""Extract and verify the current user from a Supabase JWT.
|
||||
|
||||
Tries local HS256 verification first (no network call, no SSL risk).
|
||||
Falls back to supabase.auth.get_user() only when the JWT secret is not configured.
|
||||
"""
|
||||
if not credentials:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
@@ -20,39 +79,45 @@ async def get_current_user(
|
||||
)
|
||||
|
||||
token = credentials.credentials
|
||||
supabase = get_supabase()
|
||||
|
||||
try:
|
||||
response = supabase.auth.get_user(token)
|
||||
if not response or not response.user:
|
||||
# ── Fast path: local verification ────────────────────────────────────────
|
||||
user = _verify_jwt_local(token)
|
||||
|
||||
# ── Slow path: network call (only if SUPABASE_JWT_SECRET is not set) ─────
|
||||
if user is None:
|
||||
supabase = get_supabase()
|
||||
try:
|
||||
response = supabase.auth.get_user(token)
|
||||
if not response or not response.user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired token",
|
||||
)
|
||||
user = response.user
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Auth error: {e}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired token",
|
||||
)
|
||||
user = response.user
|
||||
|
||||
# Check for suspension
|
||||
try:
|
||||
profile = supabase.table("user_profiles").select("suspended_at").eq("user_id", user.id).execute()
|
||||
if profile.data and profile.data[0].get("suspended_at"):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account suspended. Please contact support.",
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
pass # Don't block login if profile lookup fails
|
||||
|
||||
return user
|
||||
# ── Suspension check (DB, not network-auth, so still fast) ───────────────
|
||||
try:
|
||||
supabase = get_supabase()
|
||||
profile = supabase.table("user_profiles").select("suspended_at").eq("user_id", user.id).execute()
|
||||
if profile.data and profile.data[0].get("suspended_at"):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account suspended. Please contact support.",
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Auth error: {e}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired token",
|
||||
)
|
||||
except Exception:
|
||||
pass # Never block login if profile lookup fails
|
||||
|
||||
return user
|
||||
|
||||
|
||||
async def get_admin_user(
|
||||
|
||||
Reference in New Issue
Block a user