Spaces:
Sleeping

curium-intel / auth.py
Piers Lyon
Claude Opus 4.6 (1M context)
Add auth, audit logging, backup/restore, and HF Spaces deployment
560b4ce
Raw History Blame Contribute Delete
6.61 kB
"""
Authentication & role management for Curium Lead Intelligence Platform.
Two-tier auth:
- admin: full access (HUNT NOW, Council Scan, all Claude-spending actions, settings)
- viewer: read-only browsing; Claude/SMTP buttons disabled with tooltip
Credentials are bcrypt-hashed and supplied via env vars (never committed):
ADMIN_USERNAME, ADMIN_PASSWORD_HASH
VIEWER_USERNAME, VIEWER_PASSWORD_HASH
Generate hashes with: python scripts/generate_password_hashes.py
"""
import os
import streamlit as st
import bcrypt
from typing import Optional
ROLE_ADMIN = "admin"
ROLE_VIEWER = "viewer"
SESSION_USER_KEY = "auth_user"
SESSION_ROLE_KEY = "auth_role"
ADMIN_BLOCKED_TOOLTIP = "Admin only \u2014 ask Piers to run this"
# -----------------------------------------------------------------------------
# Credential lookup
# -----------------------------------------------------------------------------
def _accounts() -> dict:
"""
Return {username: (role, password_hash_bytes)} from env vars.
Missing env vars are skipped silently (e.g. only admin configured).
"""
out = {}
admin_user = os.environ.get("ADMIN_USERNAME", "").strip()
admin_hash = os.environ.get("ADMIN_PASSWORD_HASH", "").strip()
viewer_user = os.environ.get("VIEWER_USERNAME", "").strip()
viewer_hash = os.environ.get("VIEWER_PASSWORD_HASH", "").strip()
if admin_user and admin_hash:
out[admin_user] = (ROLE_ADMIN, admin_hash.encode("utf-8"))
if viewer_user and viewer_hash:
out[viewer_user] = (ROLE_VIEWER, viewer_hash.encode("utf-8"))
return out
def _verify(username: str, password: str) -> Optional[str]:
"""Return role name if creds valid, else None."""
accounts = _accounts()
if not accounts:
return None
record = accounts.get(username.strip())
if not record:
return None
role, password_hash = record
try:
if bcrypt.checkpw(password.encode("utf-8"), password_hash):
return role
except (ValueError, TypeError):
return None
return None
# -----------------------------------------------------------------------------
# Public API
# -----------------------------------------------------------------------------
def is_authenticated() -> bool:
return bool(st.session_state.get(SESSION_USER_KEY))
def current_user() -> Optional[str]:
return st.session_state.get(SESSION_USER_KEY)
def current_role() -> Optional[str]:
return st.session_state.get(SESSION_ROLE_KEY)
def is_admin() -> bool:
return current_role() == ROLE_ADMIN
def logout():
for key in (SESSION_USER_KEY, SESSION_ROLE_KEY):
if key in st.session_state:
del st.session_state[key]
def render_login_screen():
"""
Render the login form. Halts the app with st.stop() if not authenticated.
Call this at the very top of app.py BEFORE rendering anything else.
"""
if is_authenticated():
return
st.markdown(
"""
<div style="text-align:center;padding:2em 0 1em 0;">
<span style="font-size:2.2em;font-weight:800;color:#1a237e;">CURIUM</span><br>
<span style="font-size:1em;color:#78909c;">Lead Intelligence Platform</span>
</div>
""",
unsafe_allow_html=True,
)
accounts = _accounts()
if not accounts:
st.error(
"No accounts are configured. Set `ADMIN_USERNAME` / `ADMIN_PASSWORD_HASH` "
"(and optionally `VIEWER_USERNAME` / `VIEWER_PASSWORD_HASH`) in the "
"environment, then restart."
)
st.stop()
col_l, col_c, col_r = st.columns([1, 1, 1])
with col_c:
with st.form("login_form", clear_on_submit=False):
st.subheader("Sign in")
username = st.text_input("Username", autocomplete="username")
password = st.text_input("Password", type="password", autocomplete="current-password")
submitted = st.form_submit_button("Sign in", type="primary", use_container_width=True)
if submitted:
role = _verify(username, password)
if role:
st.session_state[SESSION_USER_KEY] = username.strip()
st.session_state[SESSION_ROLE_KEY] = role
# Best-effort audit log
try:
from audit_log import log_event
log_event(username.strip(), role, "login", {"result": "success"})
except Exception:
pass
st.rerun()
else:
try:
from audit_log import log_event
log_event(username.strip() or "<empty>", "?", "login", {"result": "failure"})
except Exception:
pass
st.error("Invalid username or password.")
st.stop()
def admin_only_button(label: str, key: str, help_text: Optional[str] = None,
button_type: str = "secondary", use_container_width: bool = True) -> bool:
"""
Render a button that's disabled (with tooltip) for non-admin users.
Returns True only if clicked AND the current user is admin.
"""
if is_admin():
return st.button(
label, key=key, type=button_type,
use_container_width=use_container_width,
help=help_text,
)
# viewer: render disabled with tooltip
st.button(
label, key=key, type=button_type,
use_container_width=use_container_width,
disabled=True,
help=ADMIN_BLOCKED_TOOLTIP,
)
return False
def render_user_chip():
"""
Render the small 'Signed in as X (role) | Sign out' chip.
Place near the top of the sidebar.
"""
user = current_user() or "?"
role = current_role() or "?"
role_color = "#1a237e" if role == ROLE_ADMIN else "#546e7a"
st.markdown(
f"""
<div style="font-size:0.78em;color:#546e7a;text-align:center;padding:4px 0 8px 0;">
Signed in as <b>{user}</b>
<span style="background:{role_color};color:white;padding:1px 6px;
border-radius:6px;margin-left:4px;font-size:0.85em;">{role}</span>
</div>
""",
unsafe_allow_html=True,
)
if st.button("Sign out", key="auth_signout", use_container_width=True, type="secondary"):
try:
from audit_log import log_event
log_event(user, role, "logout", {})
except Exception:
pass
logout()
st.rerun()