Spaces:
Running
Running
File size: 1,206 Bytes
e561008 | 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 | 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.")
|