-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
59 lines (45 loc) · 1.72 KB
/
auth.py
File metadata and controls
59 lines (45 loc) · 1.72 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import logging
import os
from fastapi import HTTPException, Request
logger = logging.getLogger(__name__)
AUTH_DISABLED = os.environ.get("AUTH_DISABLED", "").lower() == "true"
_firebase_initialized = False
def _init_firebase():
global _firebase_initialized
if _firebase_initialized:
return
import firebase_admin
firebase_admin.initialize_app()
_firebase_initialized = True
def _check_allowed(email: str) -> bool:
allowed = os.environ.get("ALLOWED_EMAILS", "")
if not allowed:
return True
entries = [e.strip() for e in allowed.split(",") if e.strip()]
for entry in entries:
if entry.startswith("@"):
if email.endswith(entry):
return True
elif email == entry:
return True
return False
async def verify_firebase_token(request: Request):
if AUTH_DISABLED:
dev_email = request.headers.get("X-Dev-User", "user-a@dev.local")
dev_uid = "dev_" + dev_email.replace("@", "_at_").replace(".", "_")
return {"uid": dev_uid, "email": dev_email}
_init_firebase()
from firebase_admin import auth
authorization = request.headers.get("Authorization", "")
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")
token = authorization[7:]
try:
decoded = auth.verify_id_token(token)
except Exception as e:
logger.error("Token verification failed: %s", e)
raise HTTPException(status_code=401, detail="Invalid or expired token")
email = decoded.get("email", "")
if not _check_allowed(email):
raise HTTPException(status_code=403, detail="Email not authorized")
return decoded