Spaces:
Runtime error
Runtime error
nifty-coder commited on
Commit ·
7672051
1
Parent(s): 07b69d9
Fixed errors
Browse files
main.py
CHANGED
|
@@ -14,6 +14,7 @@ import secrets
|
|
| 14 |
from datetime import datetime, timedelta
|
| 15 |
from dotenv import load_dotenv
|
| 16 |
import boto3
|
|
|
|
| 17 |
|
| 18 |
# Load local .env if present
|
| 19 |
load_dotenv()
|
|
@@ -294,39 +295,60 @@ def verify_recaptcha(token: str, action: str = 'upload') -> bool:
|
|
| 294 |
return False
|
| 295 |
|
| 296 |
# --- JWT Verification ---
|
| 297 |
-
def
|
| 298 |
"""
|
| 299 |
-
|
| 300 |
-
Returns
|
| 301 |
-
|
| 302 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
if not FIREBASE_INITIALIZED:
|
| 304 |
raise HTTPException(status_code=500, detail="Firebase not initialized")
|
| 305 |
|
| 306 |
-
|
| 307 |
-
raise HTTPException(status_code=401, detail="Missing Authorization header")
|
| 308 |
-
|
| 309 |
-
# Extract token from "Bearer <token>" format
|
| 310 |
-
parts = authorization.split(' ')
|
| 311 |
-
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
| 312 |
-
raise HTTPException(status_code=401, detail="Invalid Authorization header format")
|
| 313 |
-
|
| 314 |
-
token = parts[1]
|
| 315 |
|
| 316 |
try:
|
| 317 |
decoded_token = firebase_auth.verify_id_token(token)
|
| 318 |
uid = decoded_token.get('uid')
|
| 319 |
if not uid:
|
| 320 |
raise HTTPException(status_code=401, detail="Invalid token: missing uid")
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
except firebase_admin.exceptions.ExpiredIdTokenError:
|
| 325 |
raise HTTPException(status_code=401, detail="Token expired")
|
| 326 |
except Exception as e:
|
| 327 |
logger.error(f"Token verification failed: {e}")
|
| 328 |
raise HTTPException(status_code=401, detail="Token verification failed")
|
| 329 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
PROFILES_FILE = os.path.join(CACHE_DIR, "profiles.json")
|
| 331 |
|
| 332 |
class ProfileIn(BaseModel):
|
|
@@ -357,41 +379,12 @@ def save_profiles(data: dict) -> None:
|
|
| 357 |
except Exception:
|
| 358 |
logger.exception('Failed to save profiles file')
|
| 359 |
|
| 360 |
-
def verify_firebase_token(authorization: str | None):
|
| 361 |
-
# Development bypass
|
| 362 |
-
dev_bypass = os.environ.get('DEV_ALLOW_PROFILE_NO_AUTH', '').lower() in ('1', 'true', 'yes')
|
| 363 |
-
if dev_bypass:
|
| 364 |
-
uid, email = 'dev-user', 'dev@example.com'
|
| 365 |
-
if authorization and authorization.lower().startswith('bearer '):
|
| 366 |
-
token = authorization.split(' ', 1)[1].strip()
|
| 367 |
-
if ':' in token:
|
| 368 |
-
parts = token.split(':', 1)
|
| 369 |
-
uid = parts[0] or uid
|
| 370 |
-
if len(parts) > 1: email = parts[1] or email
|
| 371 |
-
return {'user_id': uid, 'email': email}
|
| 372 |
-
|
| 373 |
-
if not authorization or not authorization.lower().startswith('bearer '):
|
| 374 |
-
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
| 375 |
-
|
| 376 |
-
token = authorization.split(' ', 1)[1].strip()
|
| 377 |
-
if FIREBASE_INITIALIZED and firebase_auth:
|
| 378 |
-
try:
|
| 379 |
-
decoded = firebase_auth.verify_id_token(token)
|
| 380 |
-
uid = decoded.get('uid')
|
| 381 |
-
# Check for email verification
|
| 382 |
-
user_record = firebase_auth.get_user(uid)
|
| 383 |
-
if not user_record.email_verified:
|
| 384 |
-
raise HTTPException(status_code=403, detail='Email not verified. Please check your inbox.')
|
| 385 |
-
|
| 386 |
-
return {'user_id': uid, 'email': decoded.get('email')}
|
| 387 |
-
except HTTPException as he:
|
| 388 |
-
raise he
|
| 389 |
-
except Exception:
|
| 390 |
-
raise HTTPException(status_code=401, detail='Firebase token verification failed')
|
| 391 |
-
raise HTTPException(status_code=401, detail='Firebase Admin not initialized')
|
| 392 |
-
|
| 393 |
def get_current_user(authorization: str | None = Header(None)):
|
| 394 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 395 |
|
| 396 |
@app.get("/api/profile", response_model=ProfileOut)
|
| 397 |
def get_profile(user=Depends(get_current_user)):
|
|
@@ -731,11 +724,13 @@ async def process_upload(
|
|
| 731 |
)
|
| 732 |
|
| 733 |
except HTTPException as he:
|
| 734 |
-
|
|
|
|
| 735 |
raise he
|
| 736 |
except Exception as e:
|
| 737 |
-
|
| 738 |
-
|
|
|
|
| 739 |
raise HTTPException(status_code=500, detail=str(e))
|
| 740 |
|
| 741 |
|
|
@@ -759,7 +754,9 @@ def process_upload_extracted(file: UploadFile = File(...), tos_agreed: bool = Fo
|
|
| 759 |
|
| 760 |
return {"message": "Success", "extracted_files": files, "extracted_directory": extracted_dir}
|
| 761 |
except Exception as e:
|
| 762 |
-
|
|
|
|
|
|
|
| 763 |
raise HTTPException(status_code=500, detail=str(e))
|
| 764 |
|
| 765 |
@app.get('/cache/{key}')
|
|
|
|
| 14 |
from datetime import datetime, timedelta
|
| 15 |
from dotenv import load_dotenv
|
| 16 |
import boto3
|
| 17 |
+
import traceback
|
| 18 |
|
| 19 |
# Load local .env if present
|
| 20 |
load_dotenv()
|
|
|
|
| 295 |
return False
|
| 296 |
|
| 297 |
# --- JWT Verification ---
|
| 298 |
+
def get_authenticated_user(authorization: str | None) -> dict:
|
| 299 |
"""
|
| 300 |
+
Core authentication helper to verify Firebase token.
|
| 301 |
+
Returns a dictionary with {'user_id': uid, 'email': email}.
|
| 302 |
+
Includes a development bypass if DEV_ALLOW_PROFILE_NO_AUTH is set.
|
| 303 |
"""
|
| 304 |
+
# Development bypass
|
| 305 |
+
dev_bypass = os.environ.get('DEV_ALLOW_PROFILE_NO_AUTH', '').lower() in ('1', 'true', 'yes')
|
| 306 |
+
if dev_bypass:
|
| 307 |
+
uid, email = 'dev-user', 'dev@example.com'
|
| 308 |
+
if authorization and authorization.lower().startswith('bearer '):
|
| 309 |
+
token = authorization.split(' ', 1)[1].strip()
|
| 310 |
+
if ':' in token:
|
| 311 |
+
parts = token.split(':', 1)
|
| 312 |
+
uid = parts[0] or uid
|
| 313 |
+
if len(parts) > 1: email = parts[1] or email
|
| 314 |
+
return {'user_id': uid, 'email': email}
|
| 315 |
+
|
| 316 |
+
if not authorization or not authorization.lower().startswith('bearer '):
|
| 317 |
+
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
| 318 |
+
|
| 319 |
if not FIREBASE_INITIALIZED:
|
| 320 |
raise HTTPException(status_code=500, detail="Firebase not initialized")
|
| 321 |
|
| 322 |
+
token = authorization.split(' ', 1)[1].strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
|
| 324 |
try:
|
| 325 |
decoded_token = firebase_auth.verify_id_token(token)
|
| 326 |
uid = decoded_token.get('uid')
|
| 327 |
if not uid:
|
| 328 |
raise HTTPException(status_code=401, detail="Invalid token: missing uid")
|
| 329 |
+
|
| 330 |
+
# Check for email verification
|
| 331 |
+
user_record = firebase_auth.get_user(uid)
|
| 332 |
+
if not user_record.email_verified:
|
| 333 |
+
raise HTTPException(status_code=403, detail='Email not verified. Please check your inbox.')
|
| 334 |
+
|
| 335 |
+
return {'user_id': uid, 'email': decoded_token.get('email')}
|
| 336 |
+
except HTTPException as he:
|
| 337 |
+
raise he
|
| 338 |
except firebase_admin.exceptions.ExpiredIdTokenError:
|
| 339 |
raise HTTPException(status_code=401, detail="Token expired")
|
| 340 |
except Exception as e:
|
| 341 |
logger.error(f"Token verification failed: {e}")
|
| 342 |
raise HTTPException(status_code=401, detail="Token verification failed")
|
| 343 |
|
| 344 |
+
def verify_firebase_token(authorization: str | None) -> str:
|
| 345 |
+
"""
|
| 346 |
+
Legacy helper that returns only the UID string.
|
| 347 |
+
Used for S3 path construction and general auth checks.
|
| 348 |
+
"""
|
| 349 |
+
user = get_authenticated_user(authorization)
|
| 350 |
+
return user['user_id']
|
| 351 |
+
|
| 352 |
PROFILES_FILE = os.path.join(CACHE_DIR, "profiles.json")
|
| 353 |
|
| 354 |
class ProfileIn(BaseModel):
|
|
|
|
| 379 |
except Exception:
|
| 380 |
logger.exception('Failed to save profiles file')
|
| 381 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
def get_current_user(authorization: str | None = Header(None)):
|
| 383 |
+
"""
|
| 384 |
+
Dependency helper for FastAPI routes.
|
| 385 |
+
Returns the full user info dictionary.
|
| 386 |
+
"""
|
| 387 |
+
return get_authenticated_user(authorization)
|
| 388 |
|
| 389 |
@app.get("/api/profile", response_model=ProfileOut)
|
| 390 |
def get_profile(user=Depends(get_current_user)):
|
|
|
|
| 724 |
)
|
| 725 |
|
| 726 |
except HTTPException as he:
|
| 727 |
+
# Keep tmpdir for debugging instead of clearing it on error
|
| 728 |
+
logger.error(f"HTTPException in process_upload (tmpdir: {tmpdir}): {he.detail}")
|
| 729 |
raise he
|
| 730 |
except Exception as e:
|
| 731 |
+
# Keep tmpdir for debugging instead of clearing it on error
|
| 732 |
+
error_details = traceback.format_exc()
|
| 733 |
+
logger.error(f"Upload processing error (tmpdir: {tmpdir}):\n{error_details}")
|
| 734 |
raise HTTPException(status_code=500, detail=str(e))
|
| 735 |
|
| 736 |
|
|
|
|
| 754 |
|
| 755 |
return {"message": "Success", "extracted_files": files, "extracted_directory": extracted_dir}
|
| 756 |
except Exception as e:
|
| 757 |
+
# Keep tmpdir for debugging instead of clearing it on error
|
| 758 |
+
error_details = traceback.format_exc()
|
| 759 |
+
logger.error(f"Error in process_upload_extracted (tmpdir: {tmpdir}):\n{error_details}")
|
| 760 |
raise HTTPException(status_code=500, detail=str(e))
|
| 761 |
|
| 762 |
@app.get('/cache/{key}')
|