nifty-coder commited on
Commit
550d9b8
·
1 Parent(s): 57785f8

Google Auth Refinements & Profile picture

Browse files
Files changed (3) hide show
  1. README.md +1 -1
  2. __pycache__/main.cpython-314.pyc +0 -0
  3. main.py +95 -10
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: StemSplit API
3
  emoji: 🎵
4
  colorFrom: purple
5
  colorTo: pink
 
1
  ---
2
+ title: SplitSonic API
3
  emoji: 🎵
4
  colorFrom: purple
5
  colorTo: pink
__pycache__/main.cpython-314.pyc CHANGED
Binary files a/__pycache__/main.cpython-314.pyc and b/__pycache__/main.cpython-314.pyc differ
 
main.py CHANGED
@@ -37,10 +37,10 @@ default_origins = [
37
  "http://localhost:8080",
38
  "https://aimusicapp-a2b65.web.app",
39
  "https://aimusicapp-a2b65.firebaseapp.com",
40
- # "https://stemsplit.ai",
41
- # "https://www.stemsplit.ai",
42
- # "stemsplit.ai",
43
- # "www.stemsplit.ai"
44
  ]
45
  allowed_origins_env = os.environ.get('ALLOWED_ORIGINS')
46
  allowed_origins = [o.strip() for o in allowed_origins_env.split(',') if o.strip()] if allowed_origins_env else default_origins
@@ -65,7 +65,7 @@ def options_handler(request: Request):
65
 
66
  @app.get("/")
67
  def health_check():
68
- return {"status": "healthy", "message": "StemSplit Backend is running!"}
69
 
70
  # --- Utility Functions ---
71
  def find_ffmpeg() -> str:
@@ -234,9 +234,9 @@ def send_activation_email(email: str, token: str, origin: str):
234
  'api_key': SMTP2GO_API_KEY,
235
  'sender': SMTP2GO_SENDER,
236
  'to': [email],
237
- 'subject': 'Activate your StemSplit account',
238
  'html_body': f"""
239
- <h1>Welcome to StemSplit!</h1>
240
  <p>Please click the link below to activate your account. This link is valid for 15 minutes.</p>
241
  <a href="{activation_url}" style="display: inline-block; padding: 10px 20px; background-color: #007bff; color: white; text-decoration: none; border-radius: 5px;">Activate Account</a>
242
  <p>If the button doesn't work, copy and paste this link into your browser:</p>
@@ -323,7 +323,13 @@ def get_authenticated_user(authorization: str | None) -> dict:
323
 
324
  # Check for email verification
325
  user_record = firebase_auth.get_user(uid)
326
- if not user_record.email_verified:
 
 
 
 
 
 
327
  raise HTTPException(status_code=403, detail='Email not verified. Please check your inbox.')
328
 
329
  return {'user_id': uid, 'email': decoded_token.get('email')}
@@ -405,7 +411,7 @@ def get_profile(user=Depends(get_current_user)):
405
  "updated_at": p.get("updated_at")
406
  }
407
 
408
- @app.post("/api/profile", response_model=ProfileOut)
409
  def update_profile(data: ProfileIn, user=Depends(get_current_user)):
410
  profiles = load_profiles()
411
  u_id = user['user_id']
@@ -422,6 +428,53 @@ def update_profile(data: ProfileIn, user=Depends(get_current_user)):
422
  save_profiles(profiles)
423
  return {**p, "user_id": u_id, "email": user['email']}
424
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  # --- Authentication & Activation Endpoints ---
426
 
427
  class SignupRequest(BaseModel):
@@ -437,10 +490,19 @@ async def signup(request: SignupRequest, req: Request, background_tasks: Backgro
437
  raise HTTPException(status_code=500, detail="Firebase not initialized")
438
 
439
  origin = req.headers.get('origin')
440
- if not origin or origin not in allowed_origins:
441
  # Fallback to the first allowed origin if not provided or invalid (for safety)
442
  origin = allowed_origins[0] if allowed_origins else "http://localhost:8080"
443
 
 
 
 
 
 
 
 
 
 
444
  try:
445
  # Create user in Firebase with email_verified=False
446
  user = firebase_auth.create_user(
@@ -512,6 +574,29 @@ async def activate(request: ActivateRequest):
512
  logger.error(f"Activation error: {e}")
513
  raise HTTPException(status_code=500, detail="Failed to activate account.")
514
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515
  def cleanup_unactivated_users():
516
  """Delete expired activation tokens and their associated Firebase users."""
517
  if not FIREBASE_INITIALIZED:
 
37
  "http://localhost:8080",
38
  "https://aimusicapp-a2b65.web.app",
39
  "https://aimusicapp-a2b65.firebaseapp.com",
40
+ # "https://SplitSonic.ai",
41
+ # "https://www.SplitSonic.ai",
42
+ # "SplitSonic.ai",
43
+ # "www.SplitSonic.ai"
44
  ]
45
  allowed_origins_env = os.environ.get('ALLOWED_ORIGINS')
46
  allowed_origins = [o.strip() for o in allowed_origins_env.split(',') if o.strip()] if allowed_origins_env else default_origins
 
65
 
66
  @app.get("/")
67
  def health_check():
68
+ return {"status": "healthy", "message": "SplitSonic Backend is running!"}
69
 
70
  # --- Utility Functions ---
71
  def find_ffmpeg() -> str:
 
234
  'api_key': SMTP2GO_API_KEY,
235
  'sender': SMTP2GO_SENDER,
236
  'to': [email],
237
+ 'subject': 'Activate your SplitSonic account',
238
  'html_body': f"""
239
+ <h1>Welcome to SplitSonic!</h1>
240
  <p>Please click the link below to activate your account. This link is valid for 15 minutes.</p>
241
  <a href="{activation_url}" style="display: inline-block; padding: 10px 20px; background-color: #007bff; color: white; text-decoration: none; border-radius: 5px;">Activate Account</a>
242
  <p>If the button doesn't work, copy and paste this link into your browser:</p>
 
323
 
324
  # Check for email verification
325
  user_record = firebase_auth.get_user(uid)
326
+
327
+ # Check if they have a trusted provider (like Google)
328
+ providers = [p.provider_id for p in user_record.provider_data]
329
+ is_trusted_provider = 'google.com' in providers
330
+
331
+ if not user_record.email_verified and not is_trusted_provider:
332
+ logger.warning(f"Blocking unverified user: {uid} (Providers: {providers})")
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')}
 
411
  "updated_at": p.get("updated_at")
412
  }
413
 
414
+ @app.api_route("/api/profile", methods=["POST", "PUT"], response_model=ProfileOut)
415
  def update_profile(data: ProfileIn, user=Depends(get_current_user)):
416
  profiles = load_profiles()
417
  u_id = user['user_id']
 
428
  save_profiles(profiles)
429
  return {**p, "user_id": u_id, "email": user['email']}
430
 
431
+ @app.delete("/api/profile")
432
+ async def delete_profile(authorization: str = Header(...)):
433
+ """
434
+ Delete the authenticated user's profile and all associated files.
435
+ """
436
+ user = get_authenticated_user(authorization)
437
+ uid = user['user_id']
438
+
439
+ # 1. Delete all R2 files
440
+ if R2_ENABLED:
441
+ try:
442
+ user_prefixes = get_user_storage_prefixes(user)
443
+ deleted_count = 0
444
+ for prefix in user_prefixes:
445
+ while True:
446
+ response = s3_client.list_objects_v2(
447
+ Bucket=R2_BUCKET_NAME,
448
+ Prefix=prefix
449
+ )
450
+
451
+ if 'Contents' not in response:
452
+ break
453
+
454
+ delete_objects = {'Objects': [{'Key': obj['Key']} for obj in response['Contents']]}
455
+ s3_client.delete_objects(
456
+ Bucket=R2_BUCKET_NAME,
457
+ Delete=delete_objects
458
+ )
459
+ deleted_count += len(delete_objects['Objects'])
460
+
461
+ if not response.get('IsTruncated'):
462
+ break
463
+ logger.info(f"Deleted {deleted_count} files for user {uid} during profile deletion")
464
+ except Exception as e:
465
+ logger.error(f"Failed to delete files during profile deletion key={uid}: {e}")
466
+ # Proceed to delete profile even if storage cleanup fails partially
467
+ pass
468
+
469
+ # 2. Delete profile data
470
+ profiles = load_profiles()
471
+ if uid in profiles:
472
+ del profiles[uid]
473
+ save_profiles(profiles)
474
+ logger.info(f"Deleted profile data for user {uid}")
475
+
476
+ return {"message": "Profile and all data deleted successfully"}
477
+
478
  # --- Authentication & Activation Endpoints ---
479
 
480
  class SignupRequest(BaseModel):
 
490
  raise HTTPException(status_code=500, detail="Firebase not initialized")
491
 
492
  origin = req.headers.get('origin')
493
+ if origin not in allowed_origins:
494
  # Fallback to the first allowed origin if not provided or invalid (for safety)
495
  origin = allowed_origins[0] if allowed_origins else "http://localhost:8080"
496
 
497
+ # Validate password complexity
498
+ import re
499
+ password_regex = r"^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?\":{}|<>]).{8,}$"
500
+ if not re.match(password_regex, request.password):
501
+ raise HTTPException(
502
+ status_code=400,
503
+ detail="Password must be at least 8 characters long and include an uppercase letter, a number, and a special character."
504
+ )
505
+
506
  try:
507
  # Create user in Firebase with email_verified=False
508
  user = firebase_auth.create_user(
 
574
  logger.error(f"Activation error: {e}")
575
  raise HTTPException(status_code=500, detail="Failed to activate account.")
576
 
577
+ @app.get("/api/check-password-user")
578
+ def check_password_user(email: str):
579
+ """
580
+ Check if a user with the given email already has a 'password' provider.
581
+ Used by Google Auth flow to prevent duplicates.
582
+ """
583
+ if not FIREBASE_INITIALIZED:
584
+ raise HTTPException(status_code=500, detail="Firebase not initialized")
585
+
586
+ try:
587
+ user = firebase_auth.get_user_by_email(email)
588
+ # Check providers on this specific user object
589
+ providers = [p.provider_id for p in user.provider_data]
590
+ logger.info(f"Checking providers for {email}: {providers}")
591
+
592
+ has_password = 'password' in providers
593
+ return {"has_password": has_password, "providers": providers}
594
+ except firebase_admin.auth.UserNotFoundError:
595
+ return {"has_password": False, "providers": []}
596
+ except Exception as e:
597
+ logger.error(f"Error checking password user: {e}")
598
+ raise HTTPException(status_code=500, detail=str(e))
599
+
600
  def cleanup_unactivated_users():
601
  """Delete expired activation tokens and their associated Firebase users."""
602
  if not FIREBASE_INITIALIZED: