LogicGoInfotechSpaces commited on
Commit
4b2a2a9
·
1 Parent(s): 6b118c7

Fix Firebase import handling in auth endpoints - Ensure firebase_admin is always defined - Fix Firebase initialization checks - Improve error messages

Browse files
Files changed (1) hide show
  1. app/main.py +38 -22
app/main.py CHANGED
@@ -22,9 +22,13 @@ from app.database import (
22
  close_connection,
23
  )
24
  try:
25
- from firebase_admin import auth as firebase_auth
 
26
  except ImportError:
 
27
  firebase_auth = None
 
 
28
 
29
  # Import CCO colorizers
30
  try:
@@ -45,22 +49,22 @@ app = FastAPI(title="Text-Guided Image Colorization API")
45
  # -------------------------------------------------
46
  # 🔐 Firebase Initialization (ENV-based)
47
  # -------------------------------------------------
48
- try:
49
- import firebase_admin
50
- from firebase_admin import credentials, app_check
51
-
52
- firebase_json = os.getenv("FIREBASE_CREDENTIALS")
53
 
54
- if firebase_json:
55
- print("🔥 Loading Firebase credentials from ENV...")
56
- firebase_dict = json.loads(firebase_json)
57
- cred = credentials.Certificate(firebase_dict)
58
- firebase_admin.initialize_app(cred)
59
- else:
60
- print("⚠️ No Firebase credentials found. Firebase disabled.")
61
 
62
- except Exception as e:
63
- print("❌ Firebase initialization failed:", e)
 
 
64
 
65
  # -------------------------------------------------
66
  # 📁 Directories (FIXED FOR HUGGINGFACE SPACES)
@@ -247,7 +251,10 @@ async def verify_request(request: Request):
247
  1. Firebase App Check token (X-Firebase-AppCheck header) - Primary method
248
  2. Firebase Auth ID token (Authorization: Bearer header) - Fallback for auth endpoints
249
  """
250
- if not firebase_admin or not hasattr(firebase_admin, '_apps') or not firebase_admin._apps:
 
 
 
251
  return True
252
 
253
  # Primary: Check Firebase App Check token (X-Firebase-AppCheck header)
@@ -294,11 +301,14 @@ async def register_user(user_data: RegisterRequest):
294
  Register a new user with email and password.
295
  Returns Firebase ID token for immediate use.
296
  """
297
- if not firebase_admin or not hasattr(firebase_admin, '_apps') or not firebase_admin._apps:
 
 
 
298
  raise HTTPException(status_code=503, detail="Firebase not initialized")
299
 
300
  if not firebase_auth:
301
- raise HTTPException(status_code=503, detail="Firebase Admin SDK not available")
302
 
303
  try:
304
  # Create user using Firebase Admin SDK
@@ -338,11 +348,14 @@ async def login_user(credentials: LoginRequest):
338
  Login with email and password.
339
  Uses Firebase REST API to authenticate and get ID token.
340
  """
341
- if not firebase_admin or not hasattr(firebase_admin, '_apps') or not firebase_admin._apps:
 
 
 
342
  raise HTTPException(status_code=503, detail="Firebase not initialized")
343
 
344
  if not firebase_auth:
345
- raise HTTPException(status_code=503, detail="Firebase Admin SDK not available")
346
 
347
  # Firebase REST API endpoint for email/password authentication
348
  from app.config import settings
@@ -421,11 +434,14 @@ async def login_user(credentials: LoginRequest):
421
  @app.get("/auth/me")
422
  async def get_current_user(request: Request, verified: bool = Depends(verify_request)):
423
  """Get current authenticated user information"""
424
- if not firebase_admin or not hasattr(firebase_admin, '_apps') or not firebase_admin._apps:
 
 
 
425
  raise HTTPException(status_code=503, detail="Firebase not initialized")
426
 
427
  if not firebase_auth:
428
- raise HTTPException(status_code=503, detail="Firebase Admin SDK not available")
429
 
430
  # Get user from request state (set by verify_request)
431
  if hasattr(request, 'state') and hasattr(request.state, 'user'):
 
22
  close_connection,
23
  )
24
  try:
25
+ import firebase_admin
26
+ from firebase_admin import auth as firebase_auth, app_check, credentials
27
  except ImportError:
28
+ firebase_admin = None
29
  firebase_auth = None
30
+ app_check = None
31
+ credentials = None
32
 
33
  # Import CCO colorizers
34
  try:
 
49
  # -------------------------------------------------
50
  # 🔐 Firebase Initialization (ENV-based)
51
  # -------------------------------------------------
52
+ if firebase_admin:
53
+ try:
54
+ firebase_json = os.getenv("FIREBASE_CREDENTIALS")
 
 
55
 
56
+ if firebase_json:
57
+ print("🔥 Loading Firebase credentials from ENV...")
58
+ firebase_dict = json.loads(firebase_json)
59
+ cred = credentials.Certificate(firebase_dict)
60
+ firebase_admin.initialize_app(cred)
61
+ else:
62
+ print("⚠️ No Firebase credentials found. Firebase disabled.")
63
 
64
+ except Exception as e:
65
+ print("❌ Firebase initialization failed:", e)
66
+ else:
67
+ print("⚠️ Firebase Admin SDK not available. Firebase features disabled.")
68
 
69
  # -------------------------------------------------
70
  # 📁 Directories (FIXED FOR HUGGINGFACE SPACES)
 
251
  1. Firebase App Check token (X-Firebase-AppCheck header) - Primary method
252
  2. Firebase Auth ID token (Authorization: Bearer header) - Fallback for auth endpoints
253
  """
254
+ if not firebase_admin:
255
+ return True
256
+
257
+ if not hasattr(firebase_admin, '_apps') or not firebase_admin._apps:
258
  return True
259
 
260
  # Primary: Check Firebase App Check token (X-Firebase-AppCheck header)
 
301
  Register a new user with email and password.
302
  Returns Firebase ID token for immediate use.
303
  """
304
+ if not firebase_admin:
305
+ raise HTTPException(status_code=503, detail="Firebase Admin SDK not available")
306
+
307
+ if not hasattr(firebase_admin, '_apps') or not firebase_admin._apps:
308
  raise HTTPException(status_code=503, detail="Firebase not initialized")
309
 
310
  if not firebase_auth:
311
+ raise HTTPException(status_code=503, detail="Firebase Auth not available")
312
 
313
  try:
314
  # Create user using Firebase Admin SDK
 
348
  Login with email and password.
349
  Uses Firebase REST API to authenticate and get ID token.
350
  """
351
+ if not firebase_admin:
352
+ raise HTTPException(status_code=503, detail="Firebase Admin SDK not available")
353
+
354
+ if not hasattr(firebase_admin, '_apps') or not firebase_admin._apps:
355
  raise HTTPException(status_code=503, detail="Firebase not initialized")
356
 
357
  if not firebase_auth:
358
+ raise HTTPException(status_code=503, detail="Firebase Auth not available")
359
 
360
  # Firebase REST API endpoint for email/password authentication
361
  from app.config import settings
 
434
  @app.get("/auth/me")
435
  async def get_current_user(request: Request, verified: bool = Depends(verify_request)):
436
  """Get current authenticated user information"""
437
+ if not firebase_admin:
438
+ raise HTTPException(status_code=503, detail="Firebase Admin SDK not available")
439
+
440
+ if not hasattr(firebase_admin, '_apps') or not firebase_admin._apps:
441
  raise HTTPException(status_code=503, detail="Firebase not initialized")
442
 
443
  if not firebase_auth:
444
+ raise HTTPException(status_code=503, detail="Firebase Auth not available")
445
 
446
  # Get user from request state (set by verify_request)
447
  if hasattr(request, 'state') and hasattr(request.state, 'user'):