Spaces:
Sleeping
Sleeping
Update src/auth.py
Browse files6 unmodified lines789101112131415161718192018 unmodified lines394041424344458 unmodified lines5455565758596014 unmodified lines757677787980819 unmodified lines919293949596976 unmodified lines1041051061071081091101111121 unmodified line1141151161171181191201211221231247 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531542 unmodified lines1571581591601611621631641651661674 unmodified lines17217317417517617717817928 unmodified lines20820921021121221321421521621721821922022122222322422522622722822923023123223323423523623748 unmodified lines2862872882892902912922932942952962971 unmodified line2993003013023033043054 unmodified lines31031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440530 unmodified lines4364374384394404411 unmodified line44344444544644744844932 unmodified lines4824834844854864874884894904914924934944954966 unmodified lines5035045055065075085095105115125135145151 unmodified line5175185195205215225239 unmodified lines53353453553653753853915 unmodified lines5555565575586 unmodified linesfrom src.utils import get_connection# ConfigLOCKOUT_MINUTES = int(os.getenv("LOCKOUT_MINUTES", "15"))PASSWORD_EXPIRY_DAYS = int(os.getenv("PASSWORD_EXPIRY_DAYS", "90"))PASSWORD_HISTORY_SIZE = int(os.getenv("PASSWORD_HISTORY_SIZE", "3"))SESSION_TIMEOUT_MINUTES = int(os.getenv("SESSION_TIMEOUT_MINUTES", "30"))PEPPER = os.getenv("PEPPER", "")# Password policyPASS_MIN_LEN = 8_PASS_UPPER = re.compile(r"[A-Z]")_PASS_LOWER = re.compile(r"[a-z]")18 unmodified linesdef is_valid_username(u: str) -> bool:return bool(re.fullmatch(r"[A-Za-z0-9_]{3,32}", u or ""))# Hashingdef hash_password(pw: str) -> str:raw = (pw + PEPPER).encode("utf-8")return "bcrypt$" + bcrypt.hashpw(raw, bcrypt.gensalt(rounds=12)).decode("utf-8")8 unmodified linesexcept Exception:return False# Schemadef init_auth_schema():with get_connection() as conn:conn.execute("""14 unmodified linescreated_at TEXT NOT NULL,updated_at TEXT NOT NULL)""")# add indices/aux tablesconn.execute("CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)")conn.execute("""CREATE TABLE IF NOT EXISTS user_password_history (9 unmodified linestimestamp TEXT NOT NULL,email TEXT NOT NULL,user_id INTEGER,result TEXT NOT NULL,reason TEXT,client_ip TEXT,user_agent TEXT,6 unmodified linesexcept Exception:pass# src/auth.pydef bootstrap_admin_from_env():# Ensure schema exists even if called earlyinit_auth_schema()email = normalize_email(os.getenv("ADMIN_EMAIL", ""))1 unmodified linename = os.getenv("ADMIN_NAME", "admin")cust = os.getenv("ADMIN_CUSTOMER_ID", "ADMIN1")# If env not set correctly, just skip (don't crash)if not email or not pw:return# Basic validation (silent if bad; avoids crashing cold start)try:_validate_email(email)except EmailNotValidError:7 unmodified linespwh = hash_password(pw)with get_connection() as conn:conn.execute("PRAGMA busy_timeout = 3000") # handle brief concurrent access# If admin email already exists, ensure role is admin & active, then exitrow = conn.execute("SELECT id, role, is_active FROM users WHERE email=?", (email,)).fetchone()if row:uid, role, is_active = int(row[0]), str(row[1]), int(row[2])# Optional: promote to admin / re-activate if neededif role != "admin" or is_active != 1:conn.execute("UPDATE users SET role='admin', is_active=1, updated_at=? WHERE id=?",(now, uid))conn.commit()return # idempotent: nothing else to do# If table is empty or this email isn't there, insert (race-safe)# Use INSERT OR IGNORE to avoid crashing if another worker inserts firstconn.execute("""INSERT OR IGNORE INTO users(username, email, customer_id, role, password_hash,2 unmodified linesVALUES (?, ?, ?, 'admin', ?, 'bcrypt', ?, ?, ?, 1, 1)""", (name, email, cust, pwh, now, now, now))# If we inserted (or another worker raced us), ensure password history row existsrow2 = conn.execute("SELECT id FROM users WHERE email=?", (email,)).fetchone()if row2:uid = int(row2[0])# Insert history only if none exists for this userexists_hist = conn.execute("SELECT 1 FROM user_password_history WHERE user_id=? LIMIT 1", (uid,)).fetchone()4 unmodified lines)conn.commit()# Session helpersdef set_session_user(row: sqlite3.Row):st.session_state["_sid"] = st.session_state.get("_sid") or str(uuid.uuid4())st.session_state["user"] = {28 unmodified linesmins, secs = divmod(remain, 60)st.sidebar.caption(f"⏳ Session expires in {mins:02d}:{secs:02d}")# CAPTCHAdef gen_captcha(key: str):"""Generate and store a (a, b, sum) triple under session_state[key]."""a, b = secrets.randbelow(8) + 2, secrets.randbelow(8) + 2 # 2..9st.session_state[key] = (a, b, a + b)def read_captcha(key: str):"""Return the stored (a, b, sum) or (0,0,0) if missing."""return st.session_state.get(key, (0, 0, 0))def check_captcha(ans, key: str) -> bool:"""Robust comparison: accept int from number_input or numeric string."""_, _, s = read_captcha(key)try:if isinstance(ans, str):ans = ans.strip()if ans == "":return Falseans = int(ans)return int(ans) == int(s)except Exception:return False# Queriesdef user_by_email(email: str) -> sqlite3.Row | None:with get_connection() as conn:conn.row_factory = sqlite3.Row48 unmodified linesreturn Truereturn False# UIdef render_login_signup_gate():st.title("🔐 Sign in to Olist")c1, c2 = st.columns(2)# --- LOGIN ---with c1:st.subheader("Login")1 unmodified lineif CAPTCHA_KEY_LOGIN not in st.session_state:gen_captcha(CAPTCHA_KEY_LOGIN)# Refresh button OUTSIDE the formcolL, colR = st.columns([1, 1])with colL:if st.button("↻ New CAPTCHA", key="refresh_login_captcha"):4 unmodified lineswith st.form("login_form", clear_on_submit=False):email = normalize_email(st.text_input("Email"))pw = st.text_input("Password", type="password")# number_input avoids string parsing issuescap_ans = st.number_input(f"CAPTCHA: What is {a} + {b}?",min_value=0, max_value=999, step=1, format="%d", key="cap_login")submitted = st.form_submit_button("Login")if submitted:# 1) CAPTCHA checkif not check_captcha(cap_ans, CAPTCHA_KEY_LOGIN):st.error("CAPTCHA incorrect. Please try again.")gen_captcha(CAPTCHA_KEY_LOGIN) # rotate challenge after a failurereturn False # re-render with new CAPTCHA# 2) Basic fieldsif not email or not pw:st.error("Email and password required.")return False# 3) Lookup userrow = user_by_email(email)if not row:record_login_audit(email, "failure", "no_user", None)st.error("Invalid credentials.")gen_captcha(CAPTCHA_KEY_LOGIN)return False# 4) Account checksif int(row["is_active"]) != 1:record_login_audit(email, "failure", "disabled", row["id"])st.error("Account disabled. Contact admin.")return Falseif within_lock(row):record_login_audit(email, "locked", "locked", row["id"])st.error(f"Account locked until {row['locked_until']}.")return False# 5) Password verifyif not verify_password(pw, row["password_hash"]):with get_connection() as conn:fa = int(row["failed_attempts"]) + 1locked_until = Noneif fa >= 3:locked_until = (datetime.utcnow() + timedelta(minutes=LOCKOUT_MINUTES)).isoformat(timespec="seconds")fa = 0conn.execute("UPDATE users SET failed_attempts=?, locked_until=?, updated_at=? WHERE id=?",(fa, locked_until, datetime.utcnow().isoformat(timespec="seconds"), row["id"]))conn.commit()record_login_audit(email, "failure", "bad_password", row["id"])if locked_until:st.error(f"Too many attempts. Locked until {locked_until}.")else:st.error(f"Invalid credentials. Attempts left: {3 - (int(row['failed_attempts']) + 1)}")gen_captcha(CAPTCHA_KEY_LOGIN)return False# 6) Success path (unchanged from your code)with get_connection() as conn:conn.execute("UPDATE users SET failed_attempts=0, locked_until=NULL, last_login_at=?, updated_at=? WHERE id=?",(datetime.utcnow().isoformat(timespec="seconds"), datetime.utcnow().isoformat(timespec="seconds"), row["id"]))conn.commit()record_login_audit(email, "success", "", row["id"])set_session_user(row)# Force change if required/expired (your existing logic applies)if st.session_state["user"].get("require_pw_reset", 0) == 1 or is_password_expired(row):st.warning("Password change required. Please set a new password.")st.session_state["_force_change_pw"] = Truereturn Falsereturn True# SIGNUPwith c2:st.subheader("Self-Signup")with st.form("signup_form", clear_on_submit=True):username = st.text_input("Username (3–32, letters/digits/_)")email2 = normalize_email(st.text_input("Email"))cust = st.text_input("Customer ID (alphanumeric)")pw1 = st.text_input("Password", type="password")pw2 = st.text_input("Confirm Password", type="password")ok2 = st.form_submit_button("Create Account")if ok2:try:_validate_email(email2)except EmailNotValidError:30 unmodified linesreturn Falsedef _do_change_password(user_id: int, p1: str, p2: str) -> bool:errs = password_policy_errors(p1)if p1 != p2:1 unmodified lineif errs:st.error("Password policy: " + ", ".join(errs)); return Falseif cannot_reuse_password(user_id, p1):st.error("Cannot reuse your recent passwords."); return Falsenow = datetime.utcnow().isoformat(timespec="seconds")pwh = hash_password(p1)with get_connection() as conn:32 unmodified linesst.error("Session missing. Please log in again."); return_do_change_password(u["id"], p1, p2)# --- WhoAmI panel (sidebar) ---from datetime import datetime, timedeltafrom src.utils import get_connection # already imported earlier in filedef _fmt_dt(s: str | None) -> str:if not s:return "—"try:# Accept both full ISO and "%Y-%m-%d %H:%M:%S"return datetime.fromisoformat(s).strftime("%Y-%m-%d %H:%M")except Exception:try:6 unmodified linesu = st.session_state.get("user")if not u:returnwith get_connection() as conn:row = conn.execute("SELECT email, customer_id, role, last_login_at, password_changed_at, is_active ""FROM users WHERE id=?", (u["id"],)).fetchone()if not row:st.sidebar.warning("User record not found.")return1 unmodified lineemail, customer_id, role, last_login_at, pw_changed_at, is_active = rowis_active = int(is_active) == 1# password expiry infoexpires_on = Nonedays_left_str = "—"if pw_changed_at:9 unmodified linesdays_left = (expires_on - datetime.utcnow()).daysdays_left_str = f"{max(days_left, 0)} day(s)"# role badge + statusrole_badge = "🛠️ Admin" if role == "admin" else "👤 User"status_chip = "✅ Active" if is_active else "⛔ Inactive"15 unmodified lines""",unsafe_allow_html=True)6 unmodified lines78910111213141516171819202122232418 unmodified lines4344454647484950518 unmodified lines6061626364656667686970717273747576777879808182838485868788899091929314 unmodified lines1081091101111121139 unmodified lines1231241251261271281296 unmodified lines1361371381391401411421431 unmodified line1451461471481491501511521531541557 unmodified lines1631641651661671681691701711721731741751761771781791801811821832 unmodified lines1861871881891901911921931941954 unmodified lines20020120220320420520620720828 unmodified lines23723823924024124224324424548 unmodified lines2942952962972982993003013023033043053063071 unmodified line3093103113123133144 unmodified lines31932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442530 unmodified lines4564574584594604614624634641 unmodified line46646746846947047147232 unmodified lines5055065075085095105115125135145155165176 unmodified lines5245255265275285295305315325335341 unmodified line5365375385395405419 unmodified lines55155255355455555615 unmodified lines5725735746 unmodified linesfrom src.utils import get_connection# ---------------------------# Config (can be set via ENV)# ---------------------------LOCKOUT_MINUTES = int(os.getenv("LOCKOUT_MINUTES", "15"))PASSWORD_EXPIRY_DAYS = int(os.getenv("PASSWORD_EXPIRY_DAYS", "90"))PASSWORD_HISTORY_SIZE = int(os.getenv("PASSWORD_HISTORY_SIZE", "3"))SESSION_TIMEOUT_MINUTES = int(os.getenv("SESSION_TIMEOUT_MINUTES", "30"))PEPPER = os.getenv("PEPPER", "")# ---------------------------# Password policy# ---------------------------PASS_MIN_LEN = 8_PASS_UPPER = re.compile(r"[A-Z]")_PASS_LOWER = re.compile(r"[a-z]")18 unmodified linesdef is_valid_username(u: str) -> bool:return bool(re.fullmatch(r"[A-Za-z0-9_]{3,32}", u or ""))# ---------------------------# Hashing helpers# ---------------------------def hash_password(pw: str) -> str:raw = (pw + PEPPER).encode("utf-8")return "bcrypt$" + bcrypt.hashpw(raw, bcrypt.gensalt(rounds=12)).decode("utf-8")8 unmodified linesexcept Exception:return False# ---------------------------# CAPTCHA (keyed per form)# ---------------------------def gen_captcha(key: str):"""Generate and store a (a, b, sum) triple under session_state[key]."""a, b = secrets.randbelow(8) + 2, secrets.randbelow(8) + 2 # 2..9st.session_state[key] = (a, b, a + b)def read_captcha(key: str):"""Return the stored (a, b, sum) or (0,0,0) if missing."""return st.session_state.get(key, (0, 0, 0))def check_captcha(ans, key: str) -> bool:"""Robust comparison: accept int from number_input or numeric string."""_, _, s = read_captcha(key)try:if isinstance(ans, str):ans = ans.strip()if ans == "":return Falseans = int(ans)return int(ans) == int(s)except Exception:return False# ---------------------------# Schema init / bootstrap# ---------------------------def init_auth_schema():with get_connection() as conn:conn.execute("""14 unmodified linescreated_at TEXT NOT NULL,updated_at TEXT NOT NULL)""")conn.execute("CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)")conn.execute("""CREATE TABLE IF NOT EXISTS user_password_history (9 unmodified linestimestamp TEXT NOT NULL,email TEXT NOT NULL,user_id INTEGER,result TEXT NOT NULL, -- success | failure | lockedreason TEXT,client_ip TEXT,user_agent TEXT,6 unmodified linesexcept Exception:passdef bootstrap_admin_from_env():# Ensure schema even if called earlyinit_auth_schema()email = normalize_email(os.getenv("ADMIN_EMAIL", ""))1 unmodified linename = os.getenv("ADMIN_NAME", "admin")cust = os.getenv("ADMIN_CUSTOMER_ID", "ADMIN1")# If not configured, skip silentlyif not email or not pw:return# Basic validation (silent on failure)try:_validate_email(email)except EmailNotValidError:7 unmodified linespwh = hash_password(pw)with get_connection() as conn:conn.execute("PRAGMA busy_timeout = 3000")# If exists, ensure admin+active then exitrow = conn.execute("SELECT id, role, is_active FROM users WHERE email=?", (email,)).fetchone()if row:uid, role, is_active = int(row[0]), str(row[1]), int(row[2])if role != "admin" or is_active != 1:conn.execute("UPDATE users SET role='admin', is_active=1, updated_at=? WHERE id=?",(now, uid))conn.commit()return# Insert admin if not exists (race-safe)conn.execute("""INSERT OR IGNORE INTO users(username, email, customer_id, role, password_hash,2 unmodified linesVALUES (?, ?, ?, 'admin', ?, 'bcrypt', ?, ?, ?, 1, 1)""", (name, email, cust, pwh, now, now, now))# Ensure password history rowrow2 = conn.execute("SELECT id FROM users WHERE email=?", (email,)).fetchone()if row2:uid = int(row2[0])exists_hist = conn.execute("SELECT 1 FROM user_password_history WHERE user_id=? LIMIT 1", (uid,)).fetchone()4 unmodified lines)conn.commit()# ---------------------------# Session helpers# ---------------------------def set_session_user(row: sqlite3.Row):st.session_state["_sid"] = st.session_state.get("_sid") or str(uuid.uuid4())st.session_state["user"] = {28 unmodified linesmins, secs = divmod(remain, 60)st.sidebar.caption(f"⏳ Session expires in {mins:02d}:{secs:02d}")# ---------------------------# Queries / checks# ---------------------------def user_by_email(email: str) -> sqlite3.Row | None:with get_connection() as conn:conn.row_factory = sqlite3.Row48 unmodified linesreturn Truereturn False# ---------------------------# Login / Signup UI# ---------------------------def render_login_signup_gate():st.title("🔐 Sign in to Ecom ChatBot Application")c1, c2 = st.columns(2)# --- LOGIN ---with c1:st.subheader("Login")1 unmodified lineif CAPTCHA_KEY_LOGIN not in st.session_state:gen_captcha(CAPTCHA_KEY_LOGIN)colL, colR = st.columns([1, 1])with colL:if st.button("↻ New CAPTCHA", key="refresh_login_captcha"):4 unmodified lineswith st.form("login_form", clear_on_submit=False):email = normalize_email(st.text_input("Email"))pw = st.text_input("Password", type="password")cap_ans = st.number_input(f"CAPTCHA: What is {a} + {b}?",min_value=0, max_value=999, step=1, format="%d", key="cap_login")submitted = st.form_submit_button("Login")if submitted:if not check_captcha(cap_ans, CAPTCHA_KEY_LOGIN):st.error("CAPTCHA incorrect. Please try again.")gen_captcha(CAPTCHA_KEY_LOGIN)return Falseif not email or not pw:st.error("Email and password required.")return Falserow = user_by_email(email)if not row:record_login_audit(email, "failure", "no_user", None)st.error("Invalid credentials.")gen_captcha(CAPTCHA_KEY_LOGIN)return Falseif int(row["is_active"]) != 1:record_login_audit(email, "failure", "disabled", row["id"])st.error("Account disabled. Contact admin.")return Falseif within_lock(row):record_login_audit(email, "locked", "locked", row["id"])st.error(f"Account locked until {row['locked_until']}.")return Falseif not verify_password(pw, row["password_hash"]):with get_connection() as conn:fa = int(row["failed_attempts"]) + 1locked_until = Noneif fa >= 3:locked_until = (datetime.utcnow() + timedelta(minutes=LOCKOUT_MINUTES)).isoformat(timespec="seconds")fa = 0conn.execute("UPDATE users SET failed_attempts=?, locked_until=?, updated_at=? WHERE id=?",(fa, locked_until, datetime.utcnow().isoformat(timespec="seconds"), row["id"]))conn.commit()record_login_audit(email, "failure", "bad_password", row["id"])if locked_until:st.error(f"Too many attempts. Locked until {locked_until}.")else:st.error(f"Invalid credentials. Attempts left: {3 - (int(row['failed_attempts']) + 1)}")gen_captcha(CAPTCHA_KEY_LOGIN)return False# successwith get_connection() as conn:conn.execute("UPDATE users SET failed_attempts=0, locked_until=NULL, last_login_at=?, updated_at=? WHERE id=?",(datetime.utcnow().isoformat(timespec="seconds"), datetime.utcnow().isoformat(timespec="seconds"), row["id"]))conn.commit()record_login_audit(email, "success", "", row["id"])set_session_user(row)if st.session_state["user"].get("require_pw_reset", 0) == 1 or is_password_expired(row):st.warning("Password change required. Please set a new password.")st.session_state["_force_change_pw"] = Truereturn Falsereturn True# --- SIGNUP ---with c2:st.subheader("Self-Signup")CAPTCHA_KEY_SIGNUP = "_captcha_signup"if CAPTCHA_KEY_SIGNUP not in st.session_state:gen_captcha(CAPTCHA_KEY_SIGNUP)colS1, colS2 = st.columns([1, 1])with colS1:if st.button("↻ New CAPTCHA", key="refresh_signup_captcha"):gen_captcha(CAPTCHA_KEY_SIGNUP)a2, b2, _ = read_captcha(CAPTCHA_KEY_SIGNUP)with st.form("signup_form", clear_on_submit=True):username = st.text_input("Username (3–32, letters/digits/_)")email2 = normalize_email(st.text_input("Email"))cust = st.text_input("Customer ID (alphanumeric)")pw1 = st.text_input("Password", type="password")pw2 = st.text_input("Confirm Password", type="password")cap2 = st.number_input(f"CAPTCHA: What is {a2} + {b2}?",min_value=0, max_value=999, step=1, format="%d", key="cap_signup")ok2 = st.form_submit_button("Create Account")if ok2:if not check_captcha(cap2, CAPTCHA_KEY_SIGNUP):st.error("CAPTCHA incorrect. Please try again.")gen_captcha(CAPTCHA_KEY_SIGNUP)return Falsetry:_validate_email(email2)except EmailNotValidError:30 unmodified linesreturn False# ---------------------------# Change password flows# ---------------------------def _do_change_password(user_id: int, p1: str, p2: str) -> bool:errs = password_policy_errors(p1)if p1 != p2:1 unmodified lineif errs:st.error("Password policy: " + ", ".join(errs)); return Falseif cannot_reuse_password(user_id, p1):st.error(f"Cannot reuse any of your last {PASSWORD_HISTORY_SIZE} passwords."); return Falsenow = datetime.utcnow().isoformat(timespec="seconds")pwh = hash_password(p1)with get_connection() as conn:32 unmodified linesst.error("Session missing. Please log in again."); return_do_change_password(u["id"], p1, p2)# ---------------------------# WhoAmI panel (sidebar)# ---------------------------def _fmt_dt(s: str | None) -> str:if not s:return "—"try:return datetime.fromisoformat(s).strftime("%Y-%m-%d %H:%M")except Exception:try:6 unmodified linesu = st.session_state.get("user")if not u:returnwith get_connection() as conn:row = conn.execute("SELECT email, customer_id, role, last_login_at, password_changed_at, is_active ""FROM users WHERE id=?", (u["id"],)).fetchone()if not row:st.sidebar.warning("User record not found.")return1 unmodified lineemail, customer_id, role, last_login_at, pw_changed_at, is_active = rowis_active = int(is_active) == 1expires_on = Nonedays_left_str = "—"if pw_changed_at:9 unmodified linesdays_left = (expires_on - datetime.utcnow()).daysdays_left_str = f"{max(days_left, 0)} day(s)"role_badge = "🛠️ Admin" if role == "admin" else "👤 User"status_chip = "✅ Active" if is_active else "⛔ Inactive"15 unmodified lines""",unsafe_allow_html=True)
src/auth.py+136-120