nifty-coder commited on
Commit
dae4d03
·
1 Parent(s): f0c9842

Activation link

Browse files
Files changed (3) hide show
  1. __pycache__/main.cpython-314.pyc +0 -0
  2. main.py +212 -9
  3. requirements.txt +2 -1
__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
@@ -10,8 +10,13 @@ import hashlib
10
  import io
11
  import uuid
12
  import requests
13
- from datetime import datetime
 
 
14
  import boto3
 
 
 
15
  from botocore.client import Config
16
  from fastapi.middleware.cors import CORSMiddleware
17
  from fastapi.responses import FileResponse
@@ -62,7 +67,7 @@ def options_handler(request: Request):
62
 
63
  @app.get("/")
64
  def health_check():
65
- return {"status": "healthy", "message": "AI Music App Backend is running (Pure Python)"}
66
 
67
  # --- Utility Functions ---
68
 
@@ -109,13 +114,26 @@ try:
109
  from firebase_admin import credentials, auth as firebase_auth
110
  if not firebase_admin._apps:
111
  cred_json = os.environ.get('FIREBASE_CREDENTIALS')
 
 
112
  if cred_json:
113
- cred = credentials.Certificate(json.loads(cred_json))
114
- firebase_admin.initialize_app(cred)
115
- FIREBASE_INITIALIZED = True
116
- logger.info("Firebase Admin initialized via environment variable")
117
- else:
118
- # Try to find a JSON file in the project folder
 
 
 
 
 
 
 
 
 
 
 
119
  for f in os.listdir(os.path.dirname(os.path.abspath(__file__))):
120
  if f.endswith('.json') and 'firebase' in f.lower() and 'admin' in f.lower():
121
  firebase_admin.initialize_app(credentials.Certificate(f))
@@ -185,6 +203,61 @@ def check_storage_limit():
185
  detail="Storage limit reached. Please try again tomorrow."
186
  )
187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  # --- reCAPTCHA Verification ---
189
  RECAPTCHA_SECRET_KEY = os.environ.get('RECAPTCHA_SECRET_KEY')
190
 
@@ -304,7 +377,15 @@ def verify_firebase_token(authorization: str | None):
304
  if FIREBASE_INITIALIZED and firebase_auth:
305
  try:
306
  decoded = firebase_auth.verify_id_token(token)
307
- return {'user_id': decoded.get('uid'), 'email': decoded.get('email')}
 
 
 
 
 
 
 
 
308
  except Exception:
309
  raise HTTPException(status_code=401, detail='Firebase token verification failed')
310
  raise HTTPException(status_code=401, detail='Firebase Admin not initialized')
@@ -342,6 +423,128 @@ def update_profile(data: ProfileIn, user=Depends(get_current_user)):
342
  save_profiles(profiles)
343
  return {**p, "user_id": u_id, "email": user['email']}
344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  # --- Core Logic ---
346
 
347
  def run_demucs_and_extract(input_path: str, tmpdir: str) -> str:
 
10
  import io
11
  import uuid
12
  import requests
13
+ 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()
20
  from botocore.client import Config
21
  from fastapi.middleware.cors import CORSMiddleware
22
  from fastapi.responses import FileResponse
 
67
 
68
  @app.get("/")
69
  def health_check():
70
+ return {"status": "healthy", "message": "StemSplit Backend is running (Pure Python)"}
71
 
72
  # --- Utility Functions ---
73
 
 
114
  from firebase_admin import credentials, auth as firebase_auth
115
  if not firebase_admin._apps:
116
  cred_json = os.environ.get('FIREBASE_CREDENTIALS')
117
+ initialized = False
118
+
119
  if cred_json:
120
+ try:
121
+ # Try as JSON string first
122
+ cred_dict = json.loads(cred_json)
123
+ firebase_admin.initialize_app(credentials.Certificate(cred_dict))
124
+ FIREBASE_INITIALIZED = True
125
+ initialized = True
126
+ logger.info("Firebase Admin initialized via environment variable (JSON)")
127
+ except json.JSONDecodeError:
128
+ # Try as file path if NOT valid JSON
129
+ if os.path.exists(cred_json):
130
+ firebase_admin.initialize_app(credentials.Certificate(cred_json))
131
+ FIREBASE_INITIALIZED = True
132
+ initialized = True
133
+ logger.info(f"Firebase Admin initialized via environment variable (path): {cred_json}")
134
+
135
+ if not initialized:
136
+ # Fallback: Try to find a JSON file in the project folder
137
  for f in os.listdir(os.path.dirname(os.path.abspath(__file__))):
138
  if f.endswith('.json') and 'firebase' in f.lower() and 'admin' in f.lower():
139
  firebase_admin.initialize_app(credentials.Certificate(f))
 
203
  detail="Storage limit reached. Please try again tomorrow."
204
  )
205
 
206
+ # --- SMTP2GO & Activation Configuration ---
207
+ SMTP2GO_API_KEY = os.environ.get('SMTP2GO_API_KEY')
208
+ SMTP2GO_SENDER = os.environ.get('SMTP2GO_SENDER', 'noreply@aimusicapp.com')
209
+ ACTIVATIONS_FILE = os.path.join(CACHE_DIR, "activations.json")
210
+
211
+ def load_activations() -> dict:
212
+ try:
213
+ if os.path.exists(ACTIVATIONS_FILE):
214
+ with open(ACTIVATIONS_FILE, 'r', encoding='utf-8') as fh:
215
+ return json.loads(fh.read())
216
+ except Exception:
217
+ logger.exception('Failed to load activations file')
218
+ return {}
219
+
220
+ def save_activations(data: dict) -> None:
221
+ try:
222
+ with open(ACTIVATIONS_FILE, 'w', encoding='utf-8') as fh:
223
+ fh.write(json.dumps(data, ensure_ascii=False, indent=2))
224
+ except Exception:
225
+ logger.exception('Failed to save activations file')
226
+
227
+ def send_activation_email(email: str, token: str, origin: str):
228
+ if not SMTP2GO_API_KEY:
229
+ logger.warning("SMTP2GO_API_KEY not found. Skipping email sending.")
230
+ logger.info(f"Activation link for {email}: {origin}/activate?token={token}")
231
+ return
232
+
233
+ activation_url = f"{origin}/activate?token={token}"
234
+
235
+ try:
236
+ response = requests.post(
237
+ 'https://api.smtp2go.com/v3/email/send',
238
+ json={
239
+ 'api_key': SMTP2GO_API_KEY,
240
+ 'sender': SMTP2GO_SENDER,
241
+ 'to': [email],
242
+ 'subject': 'Activate your StemSplit account',
243
+ 'html_body': f"""
244
+ <h1>Welcome to StemSplit!</h1>
245
+ <p>Please click the link below to activate your account. This link is valid for 15 minutes.</p>
246
+ <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>
247
+ <p>If the button doesn't work, copy and paste this link into your browser:</p>
248
+ <p>{activation_url}</p>
249
+ """
250
+ },
251
+ timeout=10
252
+ )
253
+ result = response.json()
254
+ if response.status_code == 200 and result.get('data', {}).get('succeeded'):
255
+ logger.info(f"Activation email sent to {email}")
256
+ else:
257
+ logger.error(f"Failed to send activation email: {result}")
258
+ except Exception as e:
259
+ logger.error(f"Error sending activation email: {e}")
260
+
261
  # --- reCAPTCHA Verification ---
262
  RECAPTCHA_SECRET_KEY = os.environ.get('RECAPTCHA_SECRET_KEY')
263
 
 
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')
 
423
  save_profiles(profiles)
424
  return {**p, "user_id": u_id, "email": user['email']}
425
 
426
+ # --- Authentication & Activation Endpoints ---
427
+
428
+ class SignupRequest(BaseModel):
429
+ email: str
430
+ password: str
431
+
432
+ class ActivateRequest(BaseModel):
433
+ token: str
434
+
435
+ @app.post("/api/signup")
436
+ async def signup(request: SignupRequest, req: Request, background_tasks: BackgroundTasks):
437
+ if not FIREBASE_INITIALIZED:
438
+ raise HTTPException(status_code=500, detail="Firebase not initialized")
439
+
440
+ origin = req.headers.get('origin')
441
+ if not origin or origin not in allowed_origins:
442
+ # Fallback to the first allowed origin if not provided or invalid (for safety)
443
+ origin = allowed_origins[0] if allowed_origins else "http://localhost:5173"
444
+
445
+ try:
446
+ # Create user in Firebase with email_verified=False
447
+ user = firebase_auth.create_user(
448
+ email=request.email,
449
+ password=request.password,
450
+ email_verified=False
451
+ )
452
+
453
+ # Generate activation token
454
+ token = secrets.token_urlsafe(32)
455
+ expiry = (datetime.utcnow() + timedelta(minutes=15)).isoformat()
456
+
457
+ activations = load_activations()
458
+ activations[token] = {
459
+ "uid": user.uid,
460
+ "email": request.email,
461
+ "expires_at": expiry
462
+ }
463
+ save_activations(activations)
464
+
465
+ # Send email in background
466
+ background_tasks.add_task(send_activation_email, request.email, token, origin)
467
+ # Also clean up expired accounts
468
+ background_tasks.add_task(cleanup_unactivated_users)
469
+
470
+ return {"message": "Signup successful. Please check your email for activation link."}
471
+ except Exception as e:
472
+ logger.error(f"Signup error: {e}")
473
+ raise HTTPException(status_code=400, detail=str(e))
474
+
475
+ @app.post("/api/activate")
476
+ async def activate(request: ActivateRequest):
477
+ if not FIREBASE_INITIALIZED:
478
+ raise HTTPException(status_code=500, detail="Firebase not initialized")
479
+
480
+ activations = load_activations()
481
+ data = activations.get(request.token)
482
+
483
+ if not data:
484
+ raise HTTPException(status_code=404, detail="Invalid or expired activation token.")
485
+
486
+ expiry = datetime.fromisoformat(data['expires_at'])
487
+ if datetime.utcnow() > expiry:
488
+ # Cleanup expired user from Firebase
489
+ try:
490
+ uid = data['uid']
491
+ user = firebase_auth.get_user(uid)
492
+ if not user.email_verified:
493
+ logger.info(f"Cleaning up expired user during activation attempt: {uid}")
494
+ firebase_auth.delete_user(uid)
495
+ except Exception as cleanup_err:
496
+ logger.error(f"Failed to cleanup user during activation attempt: {cleanup_err}")
497
+
498
+ # Remove token
499
+ del activations[request.token]
500
+ save_activations(activations)
501
+ raise HTTPException(status_code=400, detail="Activation token has expired. Please sign up again.")
502
+
503
+ try:
504
+ # Mark user as verified in Firebase
505
+ firebase_auth.update_user(data['uid'], email_verified=True)
506
+
507
+ # Remove token
508
+ del activations[request.token]
509
+ save_activations(activations)
510
+
511
+ return {"message": "Account activated successfully. You can now log in."}
512
+ except Exception as e:
513
+ logger.error(f"Activation error: {e}")
514
+ raise HTTPException(status_code=500, detail="Failed to activate account.")
515
+
516
+ def cleanup_unactivated_users():
517
+ """Delete expired activation tokens and their associated Firebase users."""
518
+ if not FIREBASE_INITIALIZED:
519
+ return
520
+
521
+ activations = load_activations()
522
+ now = datetime.utcnow()
523
+ tokens_to_remove = []
524
+
525
+ for token, data in activations.items():
526
+ expiry = datetime.fromisoformat(data['expires_at'])
527
+ if now > expiry:
528
+ uid = data['uid']
529
+ try:
530
+ # Check if user is already verified (maybe by other means, though unlikely here)
531
+ user = firebase_auth.get_user(uid)
532
+ if not user.email_verified:
533
+ logger.info(f"Cleaning up unactivated user: {uid} ({data['email']})")
534
+ firebase_auth.delete_user(uid)
535
+ tokens_to_remove.append(token)
536
+ except Exception as e:
537
+ logger.error(f"Error during cleanup for user {uid}: {e}")
538
+ # Still remove token if user not found
539
+ if "user-not-found" in str(e).lower():
540
+ tokens_to_remove.append(token)
541
+
542
+ if tokens_to_remove:
543
+ for t in tokens_to_remove:
544
+ del activations[t]
545
+ save_activations(activations)
546
+ logger.info(f"Cleaned up {len(tokens_to_remove)} expired activation(s)")
547
+
548
  # --- Core Logic ---
549
 
550
  def run_demucs_and_extract(input_path: str, tmpdir: str) -> str:
requirements.txt CHANGED
@@ -11,4 +11,5 @@ torchaudio
11
  torchcodec
12
  demucs
13
  boto3>=1.34.0
14
- requests
 
 
11
  torchcodec
12
  demucs
13
  boto3>=1.34.0
14
+ requests
15
+ python-dotenv