j49_c commited on
Commit
3b62990
·
1 Parent(s): cd70431

Implement OTP email restriction, IP limits, and billing upgrade user dashboard banner

Browse files
Files changed (3) hide show
  1. app.py +97 -4
  2. index.html +22 -0
  3. login.html +77 -25
app.py CHANGED
@@ -582,12 +582,54 @@ def api_login():
582
  return jsonify({"success": True, "is_admin": False})
583
 
584
 
585
- @app.route("/api/auth/register", methods=["POST"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
586
  @rate_limited
587
- def api_register():
588
  data = request.get_json(silent=True) or {}
589
  username = (data.get("username") or "").strip()
590
  password = data.get("password") or ""
 
 
 
 
591
 
592
  if len(username) < 3 or len(username) > 20:
593
  return jsonify({"success": False, "message": "Username must be 3-20 characters"}), 400
@@ -598,24 +640,75 @@ def api_register():
598
  if username.lower() == ADMIN_USERNAME.lower():
599
  return jsonify({"success": False, "message": "Username not available"}), 400
600
 
 
601
  db = load_users()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
602
  if find_user(db, username):
603
  return jsonify({"success": False, "message": "Username already taken"}), 409
604
 
605
  new_user = {
606
  "username": username,
607
- "password_hash": generate_password_hash(password),
 
608
  "active": True,
609
  "plan": "free",
 
610
  "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
611
  }
612
  db.setdefault("users", []).append(new_user)
613
  save_users(db)
614
 
 
 
615
  session["user"] = {"username": username, "is_admin": False}
616
  session.permanent = True
617
  ensure_user_dirs(username)
618
- logger.info(f"New user registered: {username}")
619
  return jsonify({"success": True})
620
 
621
 
 
582
  return jsonify({"success": True, "is_admin": False})
583
 
584
 
585
+ import smtplib
586
+ from email.message import EmailMessage
587
+ import random
588
+
589
+ OTP_STORAGE = {}
590
+
591
+ def get_client_ip():
592
+ if request.headers.get('X-Forwarded-For'):
593
+ return request.headers.get('X-Forwarded-For').split(',')[0].strip()
594
+ return request.remote_addr or ""
595
+
596
+ def send_otp_email(to_email, code):
597
+ server = os.environ.get("SMTP_SERVER", "smtp.gmail.com")
598
+ port = int(os.environ.get("SMTP_PORT", "587"))
599
+ user = os.environ.get("SMTP_USER", "")
600
+ password = os.environ.get("SMTP_PASS", "")
601
+
602
+ if not user or not password:
603
+ logger.warning(f"SMTP not configured. Sent OTP {code} to {to_email} (Simulated)")
604
+ return True
605
+
606
+ msg = EmailMessage()
607
+ msg.set_content(f"مرحباً بك في استضافة الذئب.\n\nكود التحقق الخاص بك هو: {code}\n\nيرجى عدم مشاركة هذا الكود مع أحد.")
608
+ msg['Subject'] = "كود التحقق - استضافة الذئب"
609
+ msg['From'] = f"White Wolf Protocol <{user}>"
610
+ msg['To'] = to_email
611
+
612
+ try:
613
+ with smtplib.SMTP(server, port) as s:
614
+ s.starttls()
615
+ s.login(user, password)
616
+ s.send_message(msg)
617
+ return True
618
+ except Exception as e:
619
+ logger.error(f"Failed to send email: {e}")
620
+ return False
621
+
622
+
623
+ @app.route("/api/auth/register-otp", methods=["POST"])
624
  @rate_limited
625
+ def api_register_otp():
626
  data = request.get_json(silent=True) or {}
627
  username = (data.get("username") or "").strip()
628
  password = data.get("password") or ""
629
+ email = (data.get("email") or "").strip()
630
+
631
+ if not email or '@' not in email:
632
+ return jsonify({"success": False, "message": "البريد الإلكتروني غير صالح"}), 400
633
 
634
  if len(username) < 3 or len(username) > 20:
635
  return jsonify({"success": False, "message": "Username must be 3-20 characters"}), 400
 
640
  if username.lower() == ADMIN_USERNAME.lower():
641
  return jsonify({"success": False, "message": "Username not available"}), 400
642
 
643
+ client_ip = get_client_ip()
644
  db = load_users()
645
+
646
+ # IP CHECK
647
+ if client_ip:
648
+ for u in db.get("users", []):
649
+ if u.get("ip") == client_ip:
650
+ return jsonify({"success": False, "message": "لقد قمت مسبقاً بإنشاء حساب من هذا الجهاز"}), 403
651
+
652
+ if find_user(db, username):
653
+ return jsonify({"success": False, "message": "Username already taken"}), 409
654
+
655
+ for u in db.get("users", []):
656
+ if u.get("email") == email:
657
+ return jsonify({"success": False, "message": "Email already in use"}), 409
658
+
659
+ otp = str(random.randint(100000, 999999))
660
+ OTP_STORAGE[email] = {
661
+ "otp": otp,
662
+ "username": username,
663
+ "password": password,
664
+ "ip": client_ip,
665
+ "time": time.time()
666
+ }
667
+
668
+ if send_otp_email(email, otp):
669
+ return jsonify({"success": True, "message": "تم إرسال كود التحقق"}), 200
670
+ else:
671
+ return jsonify({"success": False, "message": "فشل في إرسال البريد الإلكتروني"}), 500
672
+
673
+
674
+ @app.route("/api/auth/register-verify", methods=["POST"])
675
+ @rate_limited
676
+ def api_register_verify():
677
+ data = request.get_json(silent=True) or {}
678
+ email = (data.get("email") or "").strip()
679
+ otp = (data.get("code") or "").strip()
680
+
681
+ record = OTP_STORAGE.get(email)
682
+ if not record or record["otp"] != otp:
683
+ return jsonify({"success": False, "message": "كود التحقق خاطئ أو منتهي الصلاحية"}), 400
684
+
685
+ if time.time() - record["time"] > 600:
686
+ return jsonify({"success": False, "message": "كود التحقق منتهي الصلاحية"}), 400
687
+
688
+ db = load_users()
689
+ username = record["username"]
690
+
691
  if find_user(db, username):
692
  return jsonify({"success": False, "message": "Username already taken"}), 409
693
 
694
  new_user = {
695
  "username": username,
696
+ "email": email,
697
+ "password_hash": generate_password_hash(record["password"]),
698
  "active": True,
699
  "plan": "free",
700
+ "ip": record["ip"],
701
  "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
702
  }
703
  db.setdefault("users", []).append(new_user)
704
  save_users(db)
705
 
706
+ del OTP_STORAGE[email]
707
+
708
  session["user"] = {"username": username, "is_admin": False}
709
  session.permanent = True
710
  ensure_user_dirs(username)
711
+ logger.info(f"New user registered: {username} from IP: {record['ip']}")
712
  return jsonify({"success": True})
713
 
714
 
index.html CHANGED
@@ -715,6 +715,18 @@
715
  </div>
716
 
717
  <div class="container" id="homeView">
 
 
 
 
 
 
 
 
 
 
 
 
718
  <div class="grid" id="cardsContainer"></div>
719
  </div>
720
 
@@ -844,6 +856,16 @@
844
 
845
  fetch('/admin').then(res => { if (!res.redirected && res.status === 200) document.getElementById('adminBtn').style.display = 'inline-flex'; });
846
 
 
 
 
 
 
 
 
 
 
 
847
  (d.servers || []).forEach(s => {
848
  const div = document.createElement('div');
849
  div.className = 'card';
 
715
  </div>
716
 
717
  <div class="container" id="homeView">
718
+ <div class="billing-panel" id="billingPanel"
719
+ style="display:none; padding: 24px; border-radius: 20px; border: 1px solid var(--border); background: rgba(50,215,75,0.05); margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
720
+ <div>
721
+ <h3 style="margin-bottom: 8px;">مرحباً <span id="pName" style="color:var(--text)"></span></h3>
722
+ <p style="color:var(--text-muted); font-size:14px; font-family: var(--mono);">PLAN: <strong id="pPlan"></strong>
723
+ | LIMIT: <span id="pBots"></span> BOTS / <span id="pMem"></span> RAM</p>
724
+ </div>
725
+ <div>
726
+ <button class="btn" style="background:var(--primary); padding: 12px 24px;"
727
+ onclick="window.open('https://t.me/j49_c', '_blank')">ترقية الاشتراك و الموارد</button>
728
+ </div>
729
+ </div>
730
  <div class="grid" id="cardsContainer"></div>
731
  </div>
732
 
 
856
 
857
  fetch('/admin').then(res => { if (!res.redirected && res.status === 200) document.getElementById('adminBtn').style.display = 'inline-flex'; });
858
 
859
+ fetch('/api/user/profile').then(res => res.json()).then(data => {
860
+ if (data.success) {
861
+ document.getElementById('billingPanel').style.display = 'flex';
862
+ document.getElementById('pName').textContent = data.username.toUpperCase();
863
+ document.getElementById('pPlan').textContent = data.plan_label.toUpperCase();
864
+ document.getElementById('pBots').textContent = data.max_bots;
865
+ document.getElementById('pMem').textContent = data.max_mem_mb + 'MB';
866
+ }
867
+ });
868
+
869
  (d.servers || []).forEach(s => {
870
  const div = document.createElement('div');
871
  div.className = 'card';
login.html CHANGED
@@ -381,19 +381,37 @@
381
 
382
  <!-- REGISTER -->
383
  <div class="form-section" id="registerForm">
384
- <div class="input-group">
385
- <input id="ru" placeholder="Choose a username" autocomplete="off" minlength="3" maxlength="20">
386
- </div>
387
- <div class="input-group">
388
- <input id="rp" placeholder="Create a password" type="password" autocomplete="new-password" minlength="6">
 
 
 
 
 
 
 
 
 
 
 
 
389
  </div>
390
- <div class="input-group">
391
- <input id="rp2" placeholder="Confirm password" type="password" autocomplete="new-password">
 
 
 
 
 
 
 
 
 
 
392
  </div>
393
- <button class="btn" onclick="doRegister()">
394
- <span id="regBtnText">CREATE ACCOUNT</span>
395
- <div class="loading-bar" id="regLoad"></div>
396
- </button>
397
  <div class="plans-info">
398
  <div class="plan-row plan-free">
399
  <span class="plan-name">🟢 Free</span>
@@ -458,37 +476,71 @@
458
  const m = document.getElementById('m');
459
  const lb = document.getElementById('regLoad');
460
  const bt = document.getElementById('regBtnText');
461
- m.textContent = '';
462
 
 
463
  const username = document.getElementById('ru').value.trim();
464
  const password = document.getElementById('rp').value;
465
- const password2 = document.getElementById('rp2').value;
466
 
467
- if (username.length < 3) { m.style.color = "var(--error)"; m.textContent = "USERNAME MIN 3 CHARACTERS"; return; }
468
- if (password.length < 6) { m.style.color = "var(--error)"; m.textContent = "PASSWORD MIN 6 CHARACTERS"; return; }
469
- if (password !== password2) { m.style.color = "var(--error)"; m.textContent = "PASSWORDS DO NOT MATCH"; return; }
470
-
471
- lb.style.display = 'block'; bt.textContent = 'CREATING...';
472
 
473
  try {
474
- const r = await fetch('/api/auth/register', {
475
  method: 'POST', headers: { 'Content-Type': 'application/json' },
476
- body: JSON.stringify({ username, password })
477
  });
478
  const d = await r.json().catch(() => ({ success: false, message: 'Connection error' }));
479
  if (!r.ok || !d.success) {
480
  m.style.color = "var(--error)";
481
  m.textContent = (d.message || 'Registration Failed').toUpperCase();
482
- lb.style.display = 'none'; bt.textContent = 'CREATE ACCOUNT';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483
  return;
484
  }
485
  m.style.color = "var(--success)";
486
- m.textContent = 'ACCOUNT CREATED. REDIRECTING...';
487
- bt.textContent = 'SUCCESS';
488
  setTimeout(() => { window.location.href = './'; }, 600);
489
  } catch (e) {
490
- m.style.color = "var(--error)"; m.textContent = "CONNECTION ERROR";
491
- lb.style.display = 'none'; bt.textContent = 'RETRY';
 
492
  }
493
  }
494
 
 
381
 
382
  <!-- REGISTER -->
383
  <div class="form-section" id="registerForm">
384
+ <div id="regStep1">
385
+ <div class="input-group">
386
+ <input id="re" placeholder="Email Address (e.g user@domain.com)" type="email" autocomplete="email">
387
+ </div>
388
+ <div class="input-group">
389
+ <input id="ru" placeholder="Choose a username" autocomplete="off" minlength="3" maxlength="20">
390
+ </div>
391
+ <div class="input-group">
392
+ <input id="rp" placeholder="Create a password" type="password" autocomplete="new-password" minlength="6">
393
+ </div>
394
+ <div class="input-group">
395
+ <input id="rp2" placeholder="Confirm password" type="password" autocomplete="new-password">
396
+ </div>
397
+ <button class="btn" onclick="doRegister()">
398
+ <span id="regBtnText">SEND VERIFICATION CODE</span>
399
+ <div class="loading-bar" id="regLoad"></div>
400
+ </button>
401
  </div>
402
+
403
+ <div id="regStep2" style="display:none; text-align:center;">
404
+ <p style="color:var(--text-muted); font-size:14px; margin-bottom: 20px;">We sent a 6-digit code to your email.
405
+ Please enter it below.</p>
406
+ <div class="input-group">
407
+ <input id="rotp" placeholder="Enter 6-digit Code" maxlength="6"
408
+ style="text-align:center; font-size: 24px; letter-spacing: 10px;">
409
+ </div>
410
+ <button class="btn" onclick="doVerify()">
411
+ <span id="verifyBtnText">CONFIRM REGISTRATION</span>
412
+ <div class="loading-bar" id="verifyLoad"></div>
413
+ </button>
414
  </div>
 
 
 
 
415
  <div class="plans-info">
416
  <div class="plan-row plan-free">
417
  <span class="plan-name">🟢 Free</span>
 
476
  const m = document.getElementById('m');
477
  const lb = document.getElementById('regLoad');
478
  const bt = document.getElementById('regBtnText');
479
+ m.textContent = ''; lb.style.display = 'block'; bt.textContent = 'WORKING...';
480
 
481
+ const email = document.getElementById('re').value.trim();
482
  const username = document.getElementById('ru').value.trim();
483
  const password = document.getElementById('rp').value;
484
+ const pass2 = document.getElementById('rp2').value;
485
 
486
+ if (!email.includes('@')) { m.style.color = "var(--error)"; m.textContent = 'INVALID EMAIL'; lb.style.display = 'none'; bt.textContent = 'SEND VERIFICATION CODE'; return; }
487
+ if (password !== pass2) { m.style.color = "var(--error)"; m.textContent = 'PASSWORDS MISMATCH'; lb.style.display = 'none'; bt.textContent = 'SEND VERIFICATION CODE'; return; }
488
+ if (password.length < 6) { m.style.color = "var(--error)"; m.textContent = 'PASSWORD MIN 6 CHARACTERS'; lb.style.display = 'none'; bt.textContent = 'SEND VERIFICATION CODE'; return; }
 
 
489
 
490
  try {
491
+ const r = await fetch('/api/auth/register-otp', {
492
  method: 'POST', headers: { 'Content-Type': 'application/json' },
493
+ body: JSON.stringify({ email, username, password })
494
  });
495
  const d = await r.json().catch(() => ({ success: false, message: 'Connection error' }));
496
  if (!r.ok || !d.success) {
497
  m.style.color = "var(--error)";
498
  m.textContent = (d.message || 'Registration Failed').toUpperCase();
499
+ lb.style.display = 'none'; bt.textContent = 'SEND VERIFICATION CODE';
500
+ return;
501
+ }
502
+
503
+ m.style.color = "var(--success)";
504
+ m.textContent = 'OTP SENT TO EMAIL';
505
+ document.getElementById('regStep1').style.display = 'none';
506
+ document.getElementById('regStep2').style.display = 'block';
507
+
508
+ } catch (e) {
509
+ m.style.color = "var(--error)";
510
+ m.textContent = 'NETWORK FAILURE';
511
+ lb.style.display = 'none'; bt.textContent = 'SEND VERIFICATION CODE';
512
+ }
513
+ }
514
+
515
+ async function doVerify() {
516
+ const m = document.getElementById('m');
517
+ const lb = document.getElementById('verifyLoad');
518
+ const bt = document.getElementById('verifyBtnText');
519
+ m.textContent = ''; lb.style.display = 'block'; bt.textContent = 'VERIFYING...';
520
+
521
+ const email = document.getElementById('re').value.trim();
522
+ const code = document.getElementById('rotp').value.trim();
523
+
524
+ try {
525
+ const r = await fetch('/api/auth/register-verify', {
526
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
527
+ body: JSON.stringify({ email, code })
528
+ });
529
+ const d = await r.json().catch(() => ({ success: false, message: 'Connection error' }));
530
+ if (!r.ok || !d.success) {
531
+ m.style.color = "var(--error)";
532
+ m.textContent = (d.message || 'Verification Failed').toUpperCase();
533
+ lb.style.display = 'none'; bt.textContent = 'CONFIRM REGISTRATION';
534
  return;
535
  }
536
  m.style.color = "var(--success)";
537
+ m.textContent = 'ACCOUNT CREATED. LOGGING IN...';
538
+ bt.textContent = 'INITIALIZING...';
539
  setTimeout(() => { window.location.href = './'; }, 600);
540
  } catch (e) {
541
+ m.style.color = "var(--error)";
542
+ m.textContent = 'NETWORK FAILURE';
543
+ lb.style.display = 'none'; bt.textContent = 'CONFIRM REGISTRATION';
544
  }
545
  }
546