from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from firebase_admin import auth as firebase_auth security = HTTPBearer() async def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security) ) -> dict: """ Extracts and verifies the Firebase JWT token from the Authorization header. Returns a dictionary containing 'uid' and optionally 'phone_number'. """ token = credentials.credentials try: # Verify the token against Firebase. This checks signature and expiration. # It automatically uses the initialized Firebase app. decoded = firebase_auth.verify_id_token(token) return { "uid": decoded["uid"], "phone_number": decoded.get("phone_number"), } except Exception as e: # The phase definition specifies returning a specific message on expiry/invalid token # but Firebase exception might be more specific. We'll return a general message # mentioning "Token expired" or invalid as requested. raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired — please re-authenticate" if "expired" in str(e).lower() else "Invalid or expired token", headers={"WWW-Authenticate": "Bearer"}, )