from __future__ import annotations import base64 import json import os from typing import Any, Dict import firebase_admin from fastapi import Depends, HTTPException, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from firebase_admin import auth, credentials bearer_scheme = HTTPBearer(auto_error=False) def initialize_firebase() -> None: if firebase_admin._apps: return service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT_JSON") service_account_base64 = os.getenv("FIREBASE_SERVICE_ACCOUNT_BASE64") service_account_path = os.getenv("FIREBASE_SERVICE_ACCOUNT_PATH") if service_account_base64: try: decoded_json = base64.b64decode(service_account_base64).decode("utf-8") service_account = json.loads(decoded_json) except (ValueError, json.JSONDecodeError) as exc: raise RuntimeError("FIREBASE_SERVICE_ACCOUNT_BASE64 is not valid base64 JSON.") from exc firebase_admin.initialize_app(credentials.Certificate(service_account)) return if service_account_json: try: service_account = json.loads(service_account_json) except json.JSONDecodeError as exc: raise RuntimeError("FIREBASE_SERVICE_ACCOUNT_JSON is not valid JSON.") from exc firebase_admin.initialize_app(credentials.Certificate(service_account)) return if service_account_path: firebase_admin.initialize_app(credentials.Certificate(service_account_path)) return raise RuntimeError( "Firebase is not configured. Set FIREBASE_SERVICE_ACCOUNT_BASE64, " "FIREBASE_SERVICE_ACCOUNT_JSON, or FIREBASE_SERVICE_ACCOUNT_PATH." ) async def require_firebase_user( credentials_header: HTTPAuthorizationCredentials = Depends(bearer_scheme), ) -> Dict[str, Any]: if credentials_header is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing Authorization header.", headers={"WWW-Authenticate": "Bearer"}, ) try: initialize_firebase() return auth.verify_id_token(credentials_header.credentials) except Exception as exc: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Invalid Firebase ID token: {exc}", headers={"WWW-Authenticate": "Bearer"}, ) from exc