SuhasGholkar commited on
Commit
e0dce50
·
verified ·
1 Parent(s): 8ba025e

Update src/auth.py

Browse files
Files changed (1) hide show
  1. src/auth.py +26 -38
src/auth.py CHANGED
@@ -1,5 +1,5 @@
1
  # src/auth.py
2
- import os, re, time, secrets, uuid, sqlite3
3
  from datetime import datetime, timedelta
4
  from pathlib import Path
5
 
@@ -18,11 +18,9 @@ PASSWORD_EXPIRY_DAYS = int(os.getenv("PASSWORD_EXPIRY_DAYS", "90"))
18
  PASSWORD_HISTORY_SIZE = int(os.getenv("PASSWORD_HISTORY_SIZE", "3"))
19
  SESSION_TIMEOUT_MINUTES = int(os.getenv("SESSION_TIMEOUT_MINUTES", "30"))
20
 
21
- # Pepper + optional fallbacks for smooth rotation/migration
22
  PEPPER = (os.getenv("PEPPER") or "").strip()
23
- PEPPER_FALLBACKS = [
24
- p.strip() for p in (os.getenv("PEPPER_FALLBACKS", "").split(",")) if p.strip()
25
- ]
26
 
27
  # =========================
28
  # Password policy
@@ -61,12 +59,14 @@ def hash_password(pw: str) -> str:
61
  def verify_password_migrating(email: str, plaintext_pw: str) -> tuple[bool, dict | None]:
62
  """
63
  Try current PEPPER, then any fallbacks, then legacy (no pepper).
64
- On match with fallback/legacy, rehash with CURRENT PEPPER and update DB.
65
  """
66
  with get_connection() as conn:
67
  conn.row_factory = sqlite3.Row
68
- row = conn.execute("SELECT id, password_hash FROM users WHERE email=?",
69
- (normalize_email(email),)).fetchone()
 
 
70
  if not row:
71
  return (False, None)
72
  stored = row["password_hash"]
@@ -109,7 +109,7 @@ def verify_password_migrating(email: str, plaintext_pw: str) -> tuple[bool, dict
109
  if bcrypt.checkpw(plaintext_pw.encode("utf-8"), hashed):
110
  now = datetime.utcnow().isoformat(timespec="seconds")
111
  new_hash = hash_password(plaintext_pw)
112
- print("[DEBUG] Setting new hash password:", new_hash, "->", ok)
113
  conn.execute(
114
  "UPDATE users SET password_hash=?, password_changed_at=?, updated_at=? WHERE id=?",
115
  (new_hash, now, now, row["id"])
@@ -148,7 +148,8 @@ def check_captcha(ans, key: str) -> bool:
148
  try:
149
  if isinstance(ans, str):
150
  ans = ans.strip()
151
- if ans == "": return False
 
152
  ans = int(ans)
153
  return int(ans) == int(s)
154
  except Exception:
@@ -349,7 +350,7 @@ def cannot_reuse_password(user_id: int, plaintext_pw: str) -> bool:
349
  return False
350
 
351
  # =========================
352
- # Login / Signup UI (side-by-side) — Streamlit container prevents phantom white box
353
  # =========================
354
  def _load_login_hero():
355
  p = os.getenv("HERO_IMAGE", "assets/login_side.jpg")
@@ -408,8 +409,7 @@ def render_signup_panel_inline():
408
  if errs:
409
  st.error("Password policy: " + ", ".join(errs)); rotate_captcha(CAPTCHA_KEY_SIGNUP); st.stop()
410
  if not check_captcha(cap2, CAPTCHA_KEY_SIGNUP):
411
- st.error("CAPTCHA incorrect. Please try again.")
412
- rotate_captcha(CAPTCHA_KEY_SIGNUP); st.stop()
413
 
414
  now = datetime.utcnow().isoformat(timespec="seconds")
415
  pwh = hash_password(pw1)
@@ -421,8 +421,10 @@ def render_signup_panel_inline():
421
  VALUES (?, ?, ?, 'user', ?, 'bcrypt', ?, ?, ?, 1, 0)
422
  """, (username, email2, cust, pwh, now, now, now))
423
  uid = conn.execute("SELECT id FROM users WHERE email=?", (email2,)).fetchone()[0]
424
- conn.execute("INSERT INTO user_password_history (user_id, password_hash, changed_at) VALUES (?, ?, ?)",
425
- (uid, pwh, now))
 
 
426
  conn.commit()
427
  st.success("Account created. Please log in.")
428
  st.session_state["_auth_view"] = "login"
@@ -432,6 +434,7 @@ def render_login_signup_gate():
432
  """
433
  Enterprise-style login: hero image (left) + login card (right).
434
  Uses a native st.container(border=True) for the card to avoid phantom blocks.
 
435
  """
436
  view = st.session_state.get("_auth_view", "login")
437
 
@@ -501,18 +504,14 @@ def render_login_signup_gate():
501
  login_clicked = st.form_submit_button("LOGIN", use_container_width=True)
502
 
503
  if refresh_captcha:
504
- gen_captcha(CAPTCHA_KEY_LOGIN)
505
- st.session_state["cap_login"] = 0
506
  st.stop()
507
 
508
  if login_clicked:
509
  # 1) CAPTCHA
510
  if not check_captcha(cap_ans, CAPTCHA_KEY_LOGIN):
511
  st.error("CAPTCHA incorrect. Please try again.")
512
- gen_captcha(CAPTCHA_KEY_LOGIN)
513
- st.session_state["cap_login"] = 0 # reset input value
514
- st.stop()
515
-
516
 
517
  # 2) Basic fields
518
  if not email or not pw:
@@ -572,7 +571,7 @@ def render_login_signup_gate():
572
 
573
  st.rerun()
574
 
575
- # Links row: Forgot + Register (styled as links by your global CSS if any)
576
  l1, l2 = st.columns([1, 1])
577
  with l1:
578
  st.caption("Forgot password?")
@@ -608,7 +607,7 @@ def _do_change_password(user_id: int, p1: str, p2: str) -> bool:
608
  (user_id, pwh, now)
609
  )
610
  conn.commit()
611
- # Optional: leave success message to the callers
612
  return True
613
 
614
  def render_force_change_password():
@@ -617,19 +616,14 @@ def render_force_change_password():
617
  p1 = st.text_input("New Password", type="password")
618
  p2 = st.text_input("Confirm Password", type="password")
619
  ok = st.form_submit_button("Update Password")
620
-
621
  if ok:
622
  u = st.session_state.get("user")
623
  if not u:
624
- st.error("Session missing. Please log in again.")
625
- return False
626
-
627
  if _do_change_password(u["id"], p1, p2):
628
- st.success("Password updated.")
629
- # Clear any gates/flags and return to main tabs
630
  st.session_state.pop("_force_change_pw", None)
631
  st.session_state["show_change_pw"] = False
632
- st.rerun() # <— important
633
  return False
634
 
635
  def render_change_password_page():
@@ -638,18 +632,13 @@ def render_change_password_page():
638
  p1 = st.text_input("New Password", type="password")
639
  p2 = st.text_input("Confirm Password", type="password")
640
  ok = st.form_submit_button("Update Password")
641
-
642
  if ok:
643
  u = st.session_state.get("user")
644
  if not u:
645
- st.error("Session missing. Please log in again.")
646
- return
647
-
648
  if _do_change_password(u["id"], p1, p2):
649
- st.success("Password updated.")
650
- # Close the change-password view and return to main tabs
651
  st.session_state["show_change_pw"] = False
652
- st.rerun() # <— important
653
 
654
  # =========================
655
  # WhoAmI panel (sidebar)
@@ -681,7 +670,6 @@ def render_whoami_sidebar():
681
  email, customer_id, role, last_login_at, pw_changed_at, is_active = row
682
  is_active = int(is_active) == 1
683
 
684
- expires_on = None
685
  days_left_str = "—"
686
  if pw_changed_at:
687
  try:
 
1
  # src/auth.py
2
+ import os, re, time, uuid, sqlite3, secrets
3
  from datetime import datetime, timedelta
4
  from pathlib import Path
5
 
 
18
  PASSWORD_HISTORY_SIZE = int(os.getenv("PASSWORD_HISTORY_SIZE", "3"))
19
  SESSION_TIMEOUT_MINUTES = int(os.getenv("SESSION_TIMEOUT_MINUTES", "30"))
20
 
21
+ # Pepper + optional fallbacks (for rotation/migration)
22
  PEPPER = (os.getenv("PEPPER") or "").strip()
23
+ PEPPER_FALLBACKS = [p.strip() for p in os.getenv("PEPPER_FALLBACKS", "").split(",") if p.strip()]
 
 
24
 
25
  # =========================
26
  # Password policy
 
59
  def verify_password_migrating(email: str, plaintext_pw: str) -> tuple[bool, dict | None]:
60
  """
61
  Try current PEPPER, then any fallbacks, then legacy (no pepper).
62
+ On fallback/legacy match, rehash with CURRENT pepper and update DB.
63
  """
64
  with get_connection() as conn:
65
  conn.row_factory = sqlite3.Row
66
+ row = conn.execute(
67
+ "SELECT id, password_hash FROM users WHERE email=?",
68
+ (normalize_email(email),)
69
+ ).fetchone()
70
  if not row:
71
  return (False, None)
72
  stored = row["password_hash"]
 
109
  if bcrypt.checkpw(plaintext_pw.encode("utf-8"), hashed):
110
  now = datetime.utcnow().isoformat(timespec="seconds")
111
  new_hash = hash_password(plaintext_pw)
112
+ print("[DEBUG] Setting new hash password:", new_hash, "->", ok)
113
  conn.execute(
114
  "UPDATE users SET password_hash=?, password_changed_at=?, updated_at=? WHERE id=?",
115
  (new_hash, now, now, row["id"])
 
148
  try:
149
  if isinstance(ans, str):
150
  ans = ans.strip()
151
+ if ans == "":
152
+ return False
153
  ans = int(ans)
154
  return int(ans) == int(s)
155
  except Exception:
 
350
  return False
351
 
352
  # =========================
353
+ # Login / Signup UI
354
  # =========================
355
  def _load_login_hero():
356
  p = os.getenv("HERO_IMAGE", "assets/login_side.jpg")
 
409
  if errs:
410
  st.error("Password policy: " + ", ".join(errs)); rotate_captcha(CAPTCHA_KEY_SIGNUP); st.stop()
411
  if not check_captcha(cap2, CAPTCHA_KEY_SIGNUP):
412
+ st.error("CAPTCHA incorrect. Please try again."); rotate_captcha(CAPTCHA_KEY_SIGNUP); st.stop()
 
413
 
414
  now = datetime.utcnow().isoformat(timespec="seconds")
415
  pwh = hash_password(pw1)
 
421
  VALUES (?, ?, ?, 'user', ?, 'bcrypt', ?, ?, ?, 1, 0)
422
  """, (username, email2, cust, pwh, now, now, now))
423
  uid = conn.execute("SELECT id FROM users WHERE email=?", (email2,)).fetchone()[0]
424
+ conn.execute(
425
+ "INSERT INTO user_password_history (user_id, password_hash, changed_at) VALUES (?, ?, ?)",
426
+ (uid, pwh, now)
427
+ )
428
  conn.commit()
429
  st.success("Account created. Please log in.")
430
  st.session_state["_auth_view"] = "login"
 
434
  """
435
  Enterprise-style login: hero image (left) + login card (right).
436
  Uses a native st.container(border=True) for the card to avoid phantom blocks.
437
+ Returns False (not logged in at end of render) — caller should handle rerun.
438
  """
439
  view = st.session_state.get("_auth_view", "login")
440
 
 
504
  login_clicked = st.form_submit_button("LOGIN", use_container_width=True)
505
 
506
  if refresh_captcha:
507
+ rotate_captcha(CAPTCHA_KEY_LOGIN)
 
508
  st.stop()
509
 
510
  if login_clicked:
511
  # 1) CAPTCHA
512
  if not check_captcha(cap_ans, CAPTCHA_KEY_LOGIN):
513
  st.error("CAPTCHA incorrect. Please try again.")
514
+ rotate_captcha(CAPTCHA_KEY_LOGIN); st.stop()
 
 
 
515
 
516
  # 2) Basic fields
517
  if not email or not pw:
 
571
 
572
  st.rerun()
573
 
574
+ # Links row: Forgot + Register
575
  l1, l2 = st.columns([1, 1])
576
  with l1:
577
  st.caption("Forgot password?")
 
607
  (user_id, pwh, now)
608
  )
609
  conn.commit()
610
+ st.success("Password updated.")
611
  return True
612
 
613
  def render_force_change_password():
 
616
  p1 = st.text_input("New Password", type="password")
617
  p2 = st.text_input("Confirm Password", type="password")
618
  ok = st.form_submit_button("Update Password")
 
619
  if ok:
620
  u = st.session_state.get("user")
621
  if not u:
622
+ st.error("Session missing. Please log in again."); return False
 
 
623
  if _do_change_password(u["id"], p1, p2):
 
 
624
  st.session_state.pop("_force_change_pw", None)
625
  st.session_state["show_change_pw"] = False
626
+ st.rerun()
627
  return False
628
 
629
  def render_change_password_page():
 
632
  p1 = st.text_input("New Password", type="password")
633
  p2 = st.text_input("Confirm Password", type="password")
634
  ok = st.form_submit_button("Update Password")
 
635
  if ok:
636
  u = st.session_state.get("user")
637
  if not u:
638
+ st.error("Session missing. Please log in again."); return
 
 
639
  if _do_change_password(u["id"], p1, p2):
 
 
640
  st.session_state["show_change_pw"] = False
641
+ st.rerun()
642
 
643
  # =========================
644
  # WhoAmI panel (sidebar)
 
670
  email, customer_id, role, last_login_at, pw_changed_at, is_active = row
671
  is_active = int(is_active) == 1
672
 
 
673
  days_left_str = "—"
674
  if pw_changed_at:
675
  try: