SuhasGholkar commited on
Commit
ffab89e
·
verified ·
1 Parent(s): 0458fc7

Update src/auth.py

Browse files
Files changed (1) hide show
  1. src/auth.py +110 -14
src/auth.py CHANGED
@@ -20,6 +20,66 @@ logging.basicConfig(
20
  )
21
  log = logging.getLogger("auth")
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  # =========================
24
  # Config (ENV-driven)
25
  # =========================
@@ -528,36 +588,53 @@ def render_login_signup_gate():
528
  st.stop()
529
 
530
  if login_clicked:
531
- # 1) CAPTCHA
532
- if not check_captcha(cap_ans, CAPTCHA_KEY_LOGIN):
533
- log.info("captcha: wrong answer (login email=%s)", email)
534
- st.error("CAPTCHA incorrect. Please try again.")
535
- rotate_captcha(CAPTCHA_KEY_LOGIN); st.stop()
536
-
 
 
 
 
 
 
537
  # 2) Basic fields
538
  if not email or not pw:
 
539
  st.error("Email and password required.")
540
  rotate_captcha(CAPTCHA_KEY_LOGIN); st.stop()
541
-
542
  # 3) Lookup user
543
  row = user_by_email(email)
544
  if not row:
 
545
  record_login_audit(email, "failure", "no_user", None)
546
  st.error("Invalid credentials.")
547
  rotate_captcha(CAPTCHA_KEY_LOGIN); st.stop()
548
-
 
 
549
  # 4) Account checks
550
  if int(row["is_active"]) != 1:
 
551
  record_login_audit(email, "failure", "disabled", row["id"])
552
  st.error("Account disabled. Contact admin.")
553
  rotate_captcha(CAPTCHA_KEY_LOGIN); st.stop()
554
  if within_lock(row):
 
555
  record_login_audit(email, "locked", "locked", row["id"])
556
  st.error(f"Account locked until {row['locked_until']}.")
557
  rotate_captcha(CAPTCHA_KEY_LOGIN); st.stop()
558
-
559
- # 5) Password verify (migration-aware)
 
 
 
560
  ok, _meta = verify_password_migrating(email, pw)
 
 
561
  if not ok:
562
  with get_connection() as conn:
563
  fa = int(row["failed_attempts"]) + 1
@@ -571,9 +648,10 @@ def render_login_signup_gate():
571
  )
572
  conn.commit()
573
  record_login_audit(email, "failure", "bad_password", row["id"])
 
574
  st.error("Invalid credentials." + (f" Locked until {locked_until}." if locked_until else ""))
575
  rotate_captcha(CAPTCHA_KEY_LOGIN); st.stop()
576
-
577
  # 6) Success
578
  with get_connection() as conn:
579
  conn.execute(
@@ -582,14 +660,15 @@ def render_login_signup_gate():
582
  )
583
  conn.commit()
584
  record_login_audit(email, "success", "", row["id"])
 
585
  set_session_user(row)
586
-
587
  # Force change if required/expired
588
  if st.session_state["user"].get("require_pw_reset", 0) == 1 or is_password_expired(row):
589
- st.warning("Password change required. Please set a new password.")
590
  st.session_state["_force_change_pw"] = True
591
  st.rerun()
592
-
593
  st.rerun()
594
 
595
  # Links row: Forgot + Register
@@ -600,6 +679,23 @@ def render_login_signup_gate():
600
  if st.button("Register here", key="go_signup_link"):
601
  st.session_state["_auth_view"] = "signup"
602
  st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603
 
604
  # Not logged in during this render
605
  return False
 
20
  )
21
  log = logging.getLogger("auth")
22
 
23
+
24
+ # Debug toggles (from env)
25
+ AUTH_DIAG = os.getenv("AUTH_DIAG", "0") == "1"
26
+ DEBUG_DISABLE_CAPTCHA = os.getenv("DEBUG_DISABLE_CAPTCHA", "0") == "1"
27
+
28
+ def debug_dump_user(email: str):
29
+ """Log user row and key fields for a given email."""
30
+ em = normalize_email(email)
31
+ with get_connection() as conn:
32
+ conn.row_factory = sqlite3.Row
33
+ row = conn.execute("SELECT * FROM users WHERE email=?", (em,)).fetchone()
34
+ if not row:
35
+ log.debug("diag: no user for email=%s", em)
36
+ return
37
+ # DO NOT log full hash; just show short prefix/length
38
+ ph = row["password_hash"] or ""
39
+ log.debug(
40
+ "diag: user id=%s email=%s role=%s active=%s failed_attempts=%s locked_until=%s "
41
+ "hash_prefix=%s... len=%s algo=%s changed_at=%s",
42
+ row["id"], row["email"], row["role"], row["is_active"], row["failed_attempts"],
43
+ row["locked_until"], ph[:12], len(ph), row["password_algo"], row["password_changed_at"]
44
+ )
45
+
46
+ def diag_try_all_peppers(email: str, plaintext_pw: str):
47
+ """Check which branch WOULD match without writing to DB."""
48
+ em = normalize_email(email)
49
+ with get_connection() as conn:
50
+ conn.row_factory = sqlite3.Row
51
+ row = conn.execute("SELECT id, password_hash FROM users WHERE email=?", (em,)).fetchone()
52
+ if not row:
53
+ log.debug("diag: try_all: no user for email=%s", em)
54
+ return "no_user"
55
+ stored = row["password_hash"] or ""
56
+ if not stored.startswith("bcrypt$"):
57
+ log.debug("diag: try_all: non-bcrypt hash for uid=%s", row["id"])
58
+ return "non_bcrypt"
59
+ hashed = stored[len("bcrypt$"):].encode("utf-8")
60
+ try:
61
+ if bcrypt.checkpw((plaintext_pw + PEPPER).encode("utf-8"), hashed):
62
+ log.debug("diag: try_all: uid=%s matches CURRENT pepper", row["id"])
63
+ return "current"
64
+ except Exception as e:
65
+ log.exception("diag: current pepper check raised: %s", e)
66
+ for old in PEPPER_FALLBACKS:
67
+ try:
68
+ if bcrypt.checkpw((plaintext_pw + old).encode("utf-8"), hashed):
69
+ log.debug("diag: try_all: uid=%s matches FALLBACK pepper", row["id"])
70
+ return "fallback"
71
+ except Exception as e:
72
+ log.exception("diag: fallback pepper check raised: %s", e)
73
+ try:
74
+ if bcrypt.checkpw(plaintext_pw.encode("utf-8"), hashed):
75
+ log.debug("diag: try_all: uid=%s matches LEGACY (no pepper)", row["id"])
76
+ return "legacy"
77
+ except Exception as e:
78
+ log.exception("diag: legacy check raised: %s", e)
79
+ log.debug("diag: try_all: uid=%s does not match any pepper path", row["id"])
80
+ return "no_match"
81
+
82
+
83
  # =========================
84
  # Config (ENV-driven)
85
  # =========================
 
588
  st.stop()
589
 
590
  if login_clicked:
591
+ log.debug("login_clicked: email=%s", email)
592
+
593
+ # 1) CAPTCHA (bypass if DEBUG_DISABLE_CAPTCHA=1)
594
+ if not DEBUG_DISABLE_CAPTCHA:
595
+ if not check_captcha(cap_ans, CAPTCHA_KEY_LOGIN):
596
+ log.info("captcha: wrong answer (login email=%s) user_ans=%s expected=%s", email, cap_ans, _sum)
597
+ st.error("CAPTCHA incorrect. Please try again.")
598
+ rotate_captcha(CAPTCHA_KEY_LOGIN)
599
+ st.stop()
600
+ else:
601
+ log.debug("captcha: bypassed by DEBUG_DISABLE_CAPTCHA=1")
602
+
603
  # 2) Basic fields
604
  if not email or not pw:
605
+ log.debug("login: missing fields email=%s has_pw=%s", bool(email), bool(pw))
606
  st.error("Email and password required.")
607
  rotate_captcha(CAPTCHA_KEY_LOGIN); st.stop()
608
+
609
  # 3) Lookup user
610
  row = user_by_email(email)
611
  if not row:
612
+ log.info("login: no user for email=%s", email)
613
  record_login_audit(email, "failure", "no_user", None)
614
  st.error("Invalid credentials.")
615
  rotate_captcha(CAPTCHA_KEY_LOGIN); st.stop()
616
+ else:
617
+ log.debug("login: found user id=%s role=%s active=%s", row["id"], row["role"], row["is_active"])
618
+
619
  # 4) Account checks
620
  if int(row["is_active"]) != 1:
621
+ log.info("login: disabled account id=%s", row["id"])
622
  record_login_audit(email, "failure", "disabled", row["id"])
623
  st.error("Account disabled. Contact admin.")
624
  rotate_captcha(CAPTCHA_KEY_LOGIN); st.stop()
625
  if within_lock(row):
626
+ log.info("login: locked account id=%s until=%s", row["id"], row["locked_until"])
627
  record_login_audit(email, "locked", "locked", row["id"])
628
  st.error(f"Account locked until {row['locked_until']}.")
629
  rotate_captcha(CAPTCHA_KEY_LOGIN); st.stop()
630
+
631
+ # 5) Password verify with diagnostics
632
+ path = diag_try_all_peppers(email, pw) # logs which branch WOULD match
633
+ log.debug("login: diag_try_all_peppers path=%s", path)
634
+
635
  ok, _meta = verify_password_migrating(email, pw)
636
+ log.debug("login: verify_password_migrating ok=%s meta=%s", ok, _meta)
637
+
638
  if not ok:
639
  with get_connection() as conn:
640
  fa = int(row["failed_attempts"]) + 1
 
648
  )
649
  conn.commit()
650
  record_login_audit(email, "failure", "bad_password", row["id"])
651
+ log.info("login: bad_password id=%s next_locked_until=%s", row["id"], locked_until)
652
  st.error("Invalid credentials." + (f" Locked until {locked_until}." if locked_until else ""))
653
  rotate_captcha(CAPTCHA_KEY_LOGIN); st.stop()
654
+
655
  # 6) Success
656
  with get_connection() as conn:
657
  conn.execute(
 
660
  )
661
  conn.commit()
662
  record_login_audit(email, "success", "", row["id"])
663
+ log.info("login: success id=%s", row["id"])
664
  set_session_user(row)
665
+
666
  # Force change if required/expired
667
  if st.session_state["user"].get("require_pw_reset", 0) == 1 or is_password_expired(row):
668
+ log.info("login: forcing password change id=%s", row["id"])
669
  st.session_state["_force_change_pw"] = True
670
  st.rerun()
671
+
672
  st.rerun()
673
 
674
  # Links row: Forgot + Register
 
679
  if st.button("Register here", key="go_signup_link"):
680
  st.session_state["_auth_view"] = "signup"
681
  st.rerun()
682
+
683
+ # Diagnostics panel (only if AUTH_DIAG=1)
684
+ if AUTH_DIAG:
685
+ with st.expander("Diagnostics (admin only)"):
686
+ st.caption("These tools log to Runtime logs. Never share logs publicly.")
687
+ test_email = st.text_input("Email to inspect (diag)", key="diag_email")
688
+ test_pw = st.text_input("Password to probe (diag)", type="password", key="diag_pw")
689
+ c1, c2 = st.columns(2)
690
+ with c1:
691
+ if st.button("Dump user row → logs", key="btn_dump_user"):
692
+ debug_dump_user(test_email)
693
+ st.success("Wrote user row to Runtime logs.")
694
+ with c2:
695
+ if st.button("Probe verify paths → logs", key="btn_probe_paths"):
696
+ res = diag_try_all_peppers(test_email, test_pw)
697
+ st.info(f"Probe result: {res} (see logs for details)")
698
+
699
 
700
  # Not logged in during this render
701
  return False