Spaces:
Sleeping
Sleeping
File size: 2,356 Bytes
395651c | 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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | from fastapi import HTTPException, Header
from app.supabase_client import get_supabase, get_supabase_for_user_jwt
async def get_current_user_id(authorization: str | None = Header(None)):
"""
Authenticate user using Supabase JWT.
Expected Header: Authorization: Bearer <token>
"""
import os
if not authorization:
raise HTTPException(
status_code=401,
detail="Authorization header missing or invalid. Use 'Bearer <token>'",
)
if os.getenv("ALLOW_TEST_BYPASS") == "true" and authorization.startswith("Test "):
return authorization.split(" ")[1]
if not authorization.startswith("Bearer "):
raise HTTPException(
status_code=401,
detail="Authorization header missing or invalid. Use 'Bearer <token>'",
)
token = authorization.split(" ")[1]
supabase = get_supabase()
try:
user_response = supabase.auth.get_user(token)
if not user_response or not user_response.user:
raise HTTPException(status_code=401, detail="Invalid session or token.")
return user_response.user.id
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=401, detail=f"Authentication failed: {str(e)}")
async def get_authenticated_supabase(authorization: str = Header(...)):
"""
Supabase client that carries the user's JWT (anon key + Authorization header).
Use for routes that should respect Row Level Security; pair with app logic as needed.
"""
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(
status_code=401,
detail="Authorization header missing or invalid. Use 'Bearer <token>'",
)
token = authorization.split(" ")[1]
supabase = get_supabase()
try:
user_response = supabase.auth.get_user(token)
if not user_response or not user_response.user:
raise HTTPException(status_code=401, detail="Invalid session or token.")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=401, detail=f"Authentication failed: {str(e)}")
try:
return get_supabase_for_user_jwt(token)
except RuntimeError as e:
raise HTTPException(status_code=503, detail=str(e))
|