""" auth.py — logging in and knowing who you are ==================================================================== WHAT THIS FILE IS: everything to do with signing in and permissions. WHAT IT DOES: sends a magic login link to the user's email, and when they click it, works out (a) who they are, by matching their email to a row in the `people` table, and (b) whether they're an admin, from that row's is_admin flag. HOW IT FITS: app.py calls login_gate() to block the app until someone's signed in, and is_admin() to decide whether to show the Admin tab. FOR WHOEVER TAKES OVER: login uses Supabase's built-in magic-link auth. A person can only get in if their login email exactly matches a people.email row — that's how access is controlled. To give someone access, add them to the people table (and to make them an admin, set is_admin = true there). ==================================================================== """ import streamlit as st from supabase_client import get_user_client, get_admin_client def _extract_person(email: str): """ Look up this email in the people directory to resolve identity + role. Uses the admin client because the people table may be RLS-restricted, and we need a reliable read to decide what the user is allowed to see. Returns a dict or None if the email isn't in the directory. """ admin = get_admin_client() res = ( admin.table("people") .select("id, full_name, role_title, email, initials, is_admin, active, community_id") .eq("email", email) .limit(1) .execute() ) rows = res.data or [] return rows[0] if rows else None def send_magic_link(email: str, redirect_to: str) -> tuple[bool, str]: """Ask Supabase to email a magic login link. Returns (ok, message).""" client = get_user_client() try: client.auth.sign_in_with_otp( { "email": email, "options": {"email_redirect_to": redirect_to}, } ) return True, "Check your email for a login link." except Exception as e: # noqa: BLE001 - surface a friendly message return False, f"Couldn't send the link: {e}" def try_complete_login_from_url() -> bool: """ On the return trip from the emailed link, complete the login. Streamlit can only read URL parameters BEFORE the '#' (hash) — it cannot see '#access_token=...' style fragments. So we rely on Supabase's PKCE / code flow, which returns '?code=...' (readable), and exchange that code for a session here. Returns True if a login was completed on this run. """ params = st.query_params # Preferred path: PKCE code flow (?code=... is visible to Streamlit). code = params.get("code") if code: client = get_user_client() try: client.auth.exchange_code_for_session({"auth_code": code}) user = client.auth.get_user().user email = user.email except Exception: st.session_state["auth_error"] = ( "That login link didn't work — it may have expired. " "Please request a new one." ) st.query_params.clear() return False return _finish_login(email) # Fallback path: some setups still return tokens as query params. access_token = params.get("access_token") refresh_token = params.get("refresh_token") if access_token and refresh_token: client = get_user_client() try: client.auth.set_session(access_token, refresh_token) email = client.auth.get_user().user.email except Exception: return False return _finish_login(email) return False def _finish_login(email: str) -> bool: """Resolve the person from the directory and store the session.""" person = _extract_person(email) if not person: st.session_state["auth_error"] = ( f"{email} isn't set up in the portal yet. Ask an admin to add you." ) st.query_params.clear() return False st.session_state["user"] = { "email": email, "person": person, "is_admin": bool(person.get("is_admin")), } st.query_params.clear() return True def current_user(): """The logged-in user dict, or None.""" return st.session_state.get("user") def is_admin() -> bool: u = current_user() return bool(u and u.get("is_admin")) def logout(): try: get_user_client().auth.sign_out() except Exception: pass st.session_state.pop("user", None) def login_gate(redirect_to: str): """ Renders the login screen and halts the app if nobody is logged in. Call this once near the top of app.py, after attempting URL login. """ if current_user(): return # already logged in, let the app continue # Show any pending error from a failed directory match. err = st.session_state.pop("auth_error", None) if err: st.warning(err) st.markdown("#### Sign in to DOBI") st.caption("Enter your Think City email and we'll send you a login link.") email = st.text_input("Email", placeholder="you@thinkcity.org", label_visibility="collapsed") if st.button("Send login link", type="primary"): if not email or "@" not in email: st.error("Enter a valid email address.") else: ok, msg = send_magic_link(email.strip().lower(), redirect_to) (st.success if ok else st.error)(msg) st.stop() # nothing below the gate renders until logged in