File size: 1,377 Bytes
1ffd0a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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"},
        )