File size: 1,372 Bytes
8800c81
 
 
 
 
 
 
a42236e
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
33
34
35
36
37
38
39
40
41
42
43
from typing import Any

from fastapi import Header, HTTPException
from firebase_admin import auth as firebase_auth

import sandbox_db

type Client = Any


class UserSession:
    def __init__(self, uid: str, email: str = ""):
        self.current_user_id = uid
        self.uid = uid
        self.email = email


def get_auth_session(authorization: str = Header(None)) -> Any:
    if not authorization or not authorization.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")
    access_token = authorization.split(" ")[1]

    if access_token == "sandbox":
        return sandbox_db.get_sandbox_client()

    try:
        decoded_token = firebase_auth.verify_id_token(access_token)
        uid = decoded_token.get("uid")
        if not uid:
            raise HTTPException(status_code=401, detail="Invalid Firebase authentication session")

        if not decoded_token.get("email_verified", False):
            raise HTTPException(
                status_code=403,
                detail="Email address is not verified. Please verify your email to access this resource.",
            )

        return UserSession(uid, decoded_token.get("email", ""))
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=401, detail=f"Authentication failed: {str(e)}")