venthrive-api / auth.py
GitHub Actions
Sync from GitHub 路 2026-06-25 17:24 UTC
e561008
Raw History Blame Contribute Delete
1.21 kB
from fastapi import Header, HTTPException, Depends
from firebase_admin import auth as firebase_auth
async def verify_firebase_token(authorization: str = Header(...)) -> dict:
"""
FastAPI dependency that verifies a Firebase ID token from the
Authorization: Bearer <token> header.
Returns the decoded token payload (contains uid, email, etc.).
Raises 401 if the token is missing, malformed, or expired.
All protected routes must declare: user = Depends(verify_firebase_token)
"""
if not authorization.startswith("Bearer "):
raise HTTPException(
status_code=401,
detail="Authorization header must be 'Bearer <token>'",
)
id_token = authorization.removeprefix("Bearer ").strip()
try:
decoded = firebase_auth.verify_id_token(id_token)
return decoded
except firebase_auth.ExpiredIdTokenError:
raise HTTPException(status_code=401, detail="Token has expired. Please sign in again.")
except firebase_auth.InvalidIdTokenError:
raise HTTPException(status_code=401, detail="Invalid token.")
except Exception:
raise HTTPException(status_code=401, detail="Authentication failed.")