Spaces:
Sleeping
Add saved-players/game-history tabs and persistent Drive access via Supabase
Browse files- Points Tracker setup now has New Game / Saved Players / Game History
tabs. Game name is picked from history (with a + New game name
fallback) instead of always free-typed; Saved Players and Game
History are read-only browsers backed by sheets_backend.list_players
and the new list_game_names helper.
- st.login() alone can never give us a refresh_token -- Streamlit's
own _auth_callback discards anything but id_token/access_token
before user code runs. Added a separate, one-time Connect Google
Drive flow (src/google_oauth.py) using access_type=offline plus
prompt=consent to force Google to issue one, and store it Fernet-
encrypted in a Supabase Postgres table (src/token_store.py). On
every subsequent login, app.py silently redeems a fresh access
token from the stored refresh_token -- no repeat consent screen.
Falls back to showing the Connect Drive button only when no valid
session token and no usable stored refresh_token exist, and clears
a revoked/invalid stored token instead of looping.
- Simplified [auth] secrets back to identity-only defaults now that
Drive scope/consent lives entirely in the new flow; added a
[supabase] secrets section (db_url, encryption_key).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Files changed (7)
- app.py+91
- pages/points_tracker.py+68-9
- requirements.txt+3
- src/bootstrap_secrets.py+4-7
- src/google_oauth.pyAdded+64
- src/sheets_backend.py+7
- src/token_store.pyAdded+59
12344 unmodified lines9101112131415162 unmodified lines192021222324import sysfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).parent / "src"))4 unmodified linesimport streamlit as stst.set_page_config(page_title="Board Game Tracker", layout="wide")with st.sidebar:if "auth" not in st.secrets:pass # no auth configured in this environment; app stays anonymous-only2 unmodified lineselse:st.caption(f"Logged in as {st.user.email}")st.button("Log out", on_click=st.logout)home_page = st.Page("pages/home.py", title="Home", url_path="home", default=True)skull_king_page = st.Page("pages/skull_king.py", title="Skull King", url_path="skull_king")1234564 unmodified lines11121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051062 unmodified lines109110111112113114115import sysimport uuidfrom datetime import datetime, timedelta, timezonefrom pathlib import Pathsys.path.insert(0, str(Path(__file__).parent / "src"))4 unmodified linesimport streamlit as stimport google_oauthimport token_storest.set_page_config(page_title="Board Game Tracker", layout="wide")def _drive_redirect_uri() -> str:return st.secrets["auth"]["redirect_uri"].removesuffix("/oauth2callback")def _store_access_token(tokens: dict) -> None:st.session_state["google_access_token"] = tokens["access_token"]expires_in = tokens.get("expires_in", 3600)st.session_state["google_access_token_expires_at"] = datetime.now(timezone.utc) + timedelta(seconds=expires_in - 60)def _access_token_valid() -> bool:expires_at = st.session_state.get("google_access_token_expires_at")return (bool(st.session_state.get("google_access_token"))and expires_at is not Noneand datetime.now(timezone.utc) < expires_at)def _handle_drive_oauth_callback() -> None:"""Completes the one-time "Connect Google Drive" exchange, if we're mid-flow."""if not st.user.is_logged_in:returncode = st.query_params.get("code")state = st.query_params.get("state")if not code or not state or state != st.session_state.get("drive_oauth_state"):returnst.session_state.pop("drive_oauth_state", None)try:tokens = google_oauth.exchange_code(st.secrets["auth"]["client_id"],st.secrets["auth"]["client_secret"],_drive_redirect_uri(),code,)except Exception:st.query_params.clear()st.error("Failed to connect Google Drive. Please try again.")returnrefresh_token = tokens.get("refresh_token")if refresh_token and "supabase" in st.secrets:token_store.save_refresh_token(st.user.email, refresh_token)_store_access_token(tokens)st.query_params.clear()st.rerun()def _ensure_drive_access() -> None:"""Populates session_state's Drive access token, silently refreshing from astored refresh_token when possible. Shows a one-time "Connect Google Drive"link only when neither a live token nor a stored refresh_token exists."""if not st.user.is_logged_in or _access_token_valid():returnif "supabase" in st.secrets:refresh_token = token_store.get_refresh_token(st.user.email)if refresh_token:try:tokens = google_oauth.refresh_access_token(st.secrets["auth"]["client_id"],st.secrets["auth"]["client_secret"],refresh_token,)_store_access_token(tokens)returnexcept Exception:token_store.delete_refresh_token(st.user.email)state = uuid.uuid4().hexst.session_state["drive_oauth_state"] = stateauthorize_url = google_oauth.build_authorize_url(st.secrets["auth"]["client_id"], _drive_redirect_uri(), state)st.link_button("Connect Google Drive", authorize_url)if "auth" in st.secrets:_handle_drive_oauth_callback()with st.sidebar:if "auth" not in st.secrets:pass # no auth configured in this environment; app stays anonymous-only2 unmodified lineselse:st.caption(f"Logged in as {st.user.email}")st.button("Log out", on_click=st.logout)_ensure_drive_access()home_page = st.Page("pages/home.py", title="Home", url_path="home", default=True)skull_king_page = st.Page("pages/skull_king.py", title="Skull King", url_path="skull_king")
25 unmodified lines262728293031323 unmodified lines36373839404142434445464748498 unmodified lines585960616263646 unmodified lines7172737475767724 unmodified lines10210310410510610725 unmodified lines"""Returns the logged-in user's Sheets workbook, or None for anonymous sessions."""if "auth" not in st.secrets or not st.user.is_logged_in:return Noneaccess_token = st.user.tokens.get("access")if not access_token:return Noneif "pt_workbook" not in st.session_state:3 unmodified linesreturn st.session_state.pt_workbookdef _setup_phase():st.subheader("Game Setup")st.session_state.pt_game_name = st.text_input("Game name (optional)",value=st.session_state.pt_game_name,placeholder="e.g. Catan, Ticket to Ride…",)st.session_state.pt_winning_score = st.number_input("Winning score (points to win)",8 unmodified linesname = st.session_state.pt_new_player.strip()if name and name not in st.session_state.pt_players:st.session_state.pt_players.append(name)wb = _get_workbook()if wb is not None:sheets.add_player(wb, name)st.session_state.pt_new_player = ""6 unmodified linesst.write("")st.button("Add Player", key="pt_add_btn", on_click=_add_player)wb = _get_workbook()if wb is not None:saved_names = [p["name"] for p in sheets.list_players(wb) if p.get("name")]remaining = [n for n in saved_names if n not in st.session_state.pt_players]24 unmodified linesst.info("Add at least 2 players to start.")def _compute_cumulative(players, scores):cumsum = {p: 0 for p in players}history = []25 unmodified lines262728293031323 unmodified lines363738394041424344454647484950515253545556575859606162636465666768697071728 unmodified lines8182838485866 unmodified lines93949596979824 unmodified lines12312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516625 unmodified lines"""Returns the logged-in user's Sheets workbook, or None for anonymous sessions."""if "auth" not in st.secrets or not st.user.is_logged_in:return Noneaccess_token = st.session_state.get("google_access_token")if not access_token:return Noneif "pt_workbook" not in st.session_state:3 unmodified linesreturn st.session_state.pt_workbook_NEW_GAME_NAME_SENTINEL = "+ New game name"def _game_name_picker(wb):past_names = sheets.list_game_names(wb) if wb is not None else []if not past_names:st.session_state.pt_game_name = st.text_input("Game name (optional)",value=st.session_state.pt_game_name,placeholder="e.g. Catan, Ticket to Ride…",)returnoptions = past_names + [_NEW_GAME_NAME_SENTINEL]current = st.session_state.pt_game_namedefault_index = options.index(current) if current in options else len(options) - 1choice = st.selectbox("Game name (optional)", options, index=default_index)if choice == _NEW_GAME_NAME_SENTINEL:st.session_state.pt_game_name = st.text_input("New game name",value="" if current in past_names else current,placeholder="e.g. Catan, Ticket to Ride…",)else:st.session_state.pt_game_name = choicedef _render_new_game_tab(wb):st.subheader("Game Setup")_game_name_picker(wb)st.session_state.pt_winning_score = st.number_input("Winning score (points to win)",8 unmodified linesname = st.session_state.pt_new_player.strip()if name and name not in st.session_state.pt_players:st.session_state.pt_players.append(name)if wb is not None:sheets.add_player(wb, name)st.session_state.pt_new_player = ""6 unmodified linesst.write("")st.button("Add Player", key="pt_add_btn", on_click=_add_player)if wb is not None:saved_names = [p["name"] for p in sheets.list_players(wb) if p.get("name")]remaining = [n for n in saved_names if n not in st.session_state.pt_players]24 unmodified linesst.info("Add at least 2 players to start.")def _render_saved_players_tab(wb):st.subheader("Saved Players")if wb is None:st.info("Log in with Google to see your saved players.")returnplayers = sheets.list_players(wb)if not players:st.caption("No saved players yet -- add one in the New Game tab.")returndf = pd.DataFrame(players)[["name", "created_at"]]st.dataframe(df, hide_index=True, width="stretch")def _render_game_history_tab(wb):st.subheader("Game History")if wb is None:st.info("Log in with Google to see your game history.")returnnames = sheets.list_game_names(wb)if not names:st.caption("No games recorded yet.")returnfor name in names:st.write(f"- {name}")def _setup_phase():wb = _get_workbook()tab_new, tab_players, tab_history = st.tabs(["New Game", "Saved Players", "Game History"])with tab_new:_render_new_game_tab(wb)with tab_players:_render_saved_players_tab(wb)with tab_history:_render_game_history_tab(wb)def _compute_cumulative(players, scores):cumsum = {p: 0 for p in players}history = []
5 unmodified lines6785 unmodified linesAuthlibhttpxtomli_w5 unmodified lines678910115 unmodified linesAuthlibhttpxtomli_wpsycopg2-binarycryptographyrequests
4 unmodified lines567891011127 unmodified lines20212223242526272829304 unmodified lines_SECRETS_PATH = Path(".streamlit/secrets.toml")_DRIVE_FILE_SCOPE = "https://www.googleapis.com/auth/drive.file"def ensure_secrets_file() -> None:if _SECRETS_PATH.exists() or "AUTH_CLIENT_ID" not in os.environ:7 unmodified lines"client_id": os.environ["AUTH_CLIENT_ID"],"client_secret": os.environ["AUTH_CLIENT_SECRET"],"server_metadata_url": "https://accounts.google.com/.well-known/openid-configuration","expose_tokens": ["access"],"client_kwargs": {"scope": f"openid email profile {_DRIVE_FILE_SCOPE}","prompt": "consent select_account",},},}_SECRETS_PATH.write_text(tomli_w.dumps(data))4 unmodified lines56789107 unmodified lines181920212223242526274 unmodified lines_SECRETS_PATH = Path(".streamlit/secrets.toml")def ensure_secrets_file() -> None:if _SECRETS_PATH.exists() or "AUTH_CLIENT_ID" not in os.environ:7 unmodified lines"client_id": os.environ["AUTH_CLIENT_ID"],"client_secret": os.environ["AUTH_CLIENT_SECRET"],"server_metadata_url": "https://accounts.google.com/.well-known/openid-configuration",},"supabase": {"db_url": os.environ["SUPABASE_DB_URL"],"encryption_key": os.environ["SUPABASE_ENCRYPTION_KEY"],},}_SECRETS_PATH.write_text(tomli_w.dumps(data))
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364from urllib.parse import urlencode
import requests
_AUTHORIZE_URL = "https://accounts.google.com/o/oauth2/v2/auth"_TOKEN_URL = "https://oauth2.googleapis.com/token"_DRIVE_FILE_SCOPE = "https://www.googleapis.com/auth/drive.file"
def build_authorize_url(client_id: str, redirect_uri: str, state: str) -> str: """Builds the Google consent-screen URL for the one-time Drive connection.
access_type=offline + prompt=consent force Google to include a refresh_token in the token response, even for a client that has been authorized before. """ params = { "client_id": client_id, "redirect_uri": redirect_uri, "response_type": "code", "scope": _DRIVE_FILE_SCOPE, "access_type": "offline", "prompt": "consent", "state": state, } return f"{_AUTHORIZE_URL}?{urlencode(params)}"
def exchange_code(client_id: str, client_secret: str, redirect_uri: str, code: str) -> dict: """Exchanges an authorization code for tokens, including a refresh_token.""" response = requests.post( _TOKEN_URL, data={ "client_id": client_id, "client_secret": client_secret, "redirect_uri": redirect_uri, "code": code, "grant_type": "authorization_code", }, timeout=10, ) response.raise_for_status() return response.json()
def refresh_access_token(client_id: str, client_secret: str, refresh_token: str) -> dict: """Mints a fresh access_token from a stored refresh_token, no browser needed.
Raises requests.HTTPError (e.g. invalid_grant) if the refresh_token has been revoked -- callers should delete the stored token and prompt the user to reconnect Drive. """ response = requests.post( _TOKEN_URL, data={ "client_id": client_id, "client_secret": client_secret, "refresh_token": refresh_token, "grant_type": "refresh_token", }, timeout=10, ) response.raise_for_status() return response.json()40 unmodified lines41424344454640 unmodified linesreturn ws.get_all_records()def add_player(wb: gspread.Spreadsheet, name: str) -> str:ws = wb.worksheet("players")existing = ws.get_all_records()40 unmodified lines4142434445464748495051525340 unmodified linesreturn ws.get_all_records()def list_game_names(wb: gspread.Spreadsheet) -> list[str]:"""Distinct game names played, most-recently-used first."""ws = wb.worksheet("games_played")names = [row["game_name"] for row in ws.get_all_records() if row.get("game_name")]return list(dict.fromkeys(reversed(names)))def add_player(wb: gspread.Spreadsheet, name: str) -> str:ws = wb.worksheet("players")existing = ws.get_all_records()
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import psycopg2import streamlit as stfrom cryptography.fernet import Fernet
_TABLE_DDL = """CREATE TABLE IF NOT EXISTS user_refresh_tokens ( email TEXT PRIMARY KEY, encrypted_refresh_token TEXT NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT now())"""
@st.cache_resourcedef _get_conn(): conn = psycopg2.connect(st.secrets["supabase"]["db_url"]) conn.autocommit = True with conn.cursor() as cur: cur.execute(_TABLE_DDL) return conn
def _fernet() -> Fernet: return Fernet(st.secrets["supabase"]["encryption_key"])
def save_refresh_token(email: str, refresh_token: str) -> None: encrypted = _fernet().encrypt(refresh_token.encode()).decode() conn = _get_conn() with conn.cursor() as cur: cur.execute( """ INSERT INTO user_refresh_tokens (email, encrypted_refresh_token, updated_at) VALUES (%s, %s, now()) ON CONFLICT (email) DO UPDATE SET encrypted_refresh_token = EXCLUDED.encrypted_refresh_token, updated_at = now() """, (email, encrypted), )
def get_refresh_token(email: str) -> str | None: conn = _get_conn() with conn.cursor() as cur: cur.execute( "SELECT encrypted_refresh_token FROM user_refresh_tokens WHERE email = %s", (email,), ) row = cur.fetchone() if row is None: return None return _fernet().decrypt(row[0].encode()).decode()
def delete_refresh_token(email: str) -> None: conn = _get_conn() with conn.cursor() as cur: cur.execute("DELETE FROM user_refresh_tokens WHERE email = %s", (email,))