Arko006 commited on
Commit
0209cfd
·
verified ·
1 Parent(s): bb57c81

Upload firebase_auth.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. firebase_auth.py +64 -0
firebase_auth.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import warnings
4
+
5
+ warnings.filterwarnings("ignore", category=FutureWarning, module="google")
6
+
7
+ import firebase_admin
8
+ from firebase_admin import credentials, auth, firestore
9
+
10
+ _app = None
11
+ _db = None
12
+
13
+
14
+ def init_firebase():
15
+ global _app, _db
16
+ if _app is not None:
17
+ return
18
+
19
+ from config import (
20
+ FIREBASE_PROJECT_ID, FIREBASE_PRIVATE_KEY,
21
+ FIREBASE_PRIVATE_KEY_ID, FIREBASE_CLIENT_EMAIL, FIREBASE_CLIENT_ID,
22
+ )
23
+
24
+ if FIREBASE_PRIVATE_KEY and FIREBASE_CLIENT_EMAIL:
25
+ cred_dict = {
26
+ "type": "service_account",
27
+ "project_id": FIREBASE_PROJECT_ID,
28
+ "private_key_id": FIREBASE_PRIVATE_KEY_ID,
29
+ "private_key": FIREBASE_PRIVATE_KEY,
30
+ "client_email": FIREBASE_CLIENT_EMAIL,
31
+ "client_id": FIREBASE_CLIENT_ID,
32
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
33
+ "token_uri": "https://oauth2.googleapis.com/token",
34
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
35
+ "client_x509_cert_url": f"https://www.googleapis.com/robot/v1/metadata/x509/{FIREBASE_CLIENT_EMAIL.replace('@', '%40')}",
36
+ "universe_domain": "googleapis.com",
37
+ }
38
+ cred = credentials.Certificate(cred_dict)
39
+ elif os.path.exists("firebase-key.json"):
40
+ cred = credentials.Certificate("firebase-key.json")
41
+ else:
42
+ raise RuntimeError("No Firebase credentials found")
43
+
44
+ _app = firebase_admin.initialize_app(cred)
45
+ _db = firestore.client(database_id="default")
46
+
47
+
48
+ def get_db():
49
+ if _db is None:
50
+ init_firebase()
51
+ return _db
52
+
53
+
54
+ async def verify_token(authorization: str) -> dict:
55
+ if not authorization.startswith("Bearer "):
56
+ from fastapi import HTTPException
57
+ raise HTTPException(status_code=401, detail="Invalid authorization header")
58
+ token = authorization[7:]
59
+ try:
60
+ decoded = auth.verify_id_token(token)
61
+ return decoded
62
+ except Exception:
63
+ from fastapi import HTTPException
64
+ raise HTTPException(status_code=401, detail="Invalid or expired token")