Spaces:
Sleeping
Sleeping
Commit ·
5d4959a
1
Parent(s): 7e1ff1d
Add optional Google login with Sheets-backed persistence for Points Tracker
Browse filesAnonymous play is unchanged. Logging in via the sidebar provisions a
per-user Google Sheet (owned by a service account) with players and
games_played worksheets, and Points Tracker writes player/round data
to it as you play. Secrets are gitignored locally and can be assembled
from individual env vars on deploy (src/bootstrap_secrets.py) so
nothing sensitive needs to live in the image.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Files changed (7)
- .gitignoreAdded+7
- README.md+49
- app.py+18
- pages/points_tracker.py+42
- requirements.txt+5-1
- src/bootstrap_secrets.pyAdded+40
- src/sheets_backend.pyAdded+95
1234567.venv/__pycache__/*.pyc.streamlit/secrets.tomlclient_secret_*.json*.iam.gserviceaccount.com.jsonpoetic-chariot-*.json17 unmodified lines18192017 unmodified linesIf you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).17 unmodified lines1819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686917 unmodified linesIf you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).## Persistence setup (Google login + Sheets)The app works fully anonymously with no setup. Logging in with Google (buttonin the sidebar) additionally persists your players and round history to aGoogle Sheet owned by a service account.### One-time Google Cloud setup1. Enable the **Google Sheets API** and **Google Drive API** on a GCP project.2. Create an OAuth 2.0 **Web application** Client ID for login; add yourapp's URL(s) as authorized redirect URIs (e.g. `http://localhost:8501` forlocal dev).3. Create a **Service Account**, download its JSON key. Service accounts haveno Drive storage quota of their own, so:- Create a folder in a real Google Drive account, share it with theservice account's `client_email` as **Editor**, and copy the folder IDfrom its URL. This becomes `shared_folder_id` below.4. Run the one-time index-spreadsheet creation (see `src/sheets_backend.py`,`get_or_create_user_workbook` needs an index spreadsheet — create one viathe service account inside the shared folder and note its ID).### Local dev — `.streamlit/secrets.toml` (gitignored, never commit this)```toml[auth]redirect_uri = "http://localhost:8501"cookie_secret = "<random string>"client_id = "<oauth client id>"client_secret = "<oauth client secret>"server_metadata_url = "https://accounts.google.com/.well-known/openid-configuration"[gcp_service_account]# ...full service account JSON fields...[sheets]index_spreadsheet_id = "<id of the index spreadsheet>"shared_folder_id = "<id of the Drive folder shared with the service account>"```### Hugging Face Space deploy`st.login()` only reads `st.secrets`, so `src/bootstrap_secrets.py` assembles`.streamlit/secrets.toml` at startup from individual Space secrets (Settings →Variables and secrets), so nothing sensitive needs to live in the repo or theimage:`AUTH_CLIENT_ID`, `AUTH_CLIENT_SECRET`, `AUTH_COOKIE_SECRET`,`AUTH_REDIRECT_URI` (your Space's public URL), `GCP_PROJECT_ID`,`GCP_PRIVATE_KEY_ID`, `GCP_PRIVATE_KEY` (paste with literal `\n` fornewlines), `GCP_CLIENT_EMAIL`, `GCP_CLIENT_ID`, `GCP_CLIENT_X509_CERT_URL`,`SHEETS_INDEX_ID`, `SHEETS_SHARED_FOLDER_ID`.
1234567import streamlit as stst.set_page_config(page_title="Board Game Tracker", layout="wide")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")dungeon_draft_page = st.Page("pages/dungeon_draft.py", title="Dungeon Draft", url_path="dungeon_draft")12345678910111213141516171819202122232425import sysfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).parent / "src"))from bootstrap_secrets import ensure_secrets_fileensure_secrets_file()import 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-onlyelif not st.user.is_logged_in:st.button("Log in with Google", on_click=st.login)else: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")dungeon_draft_page = st.Page("pages/dungeon_draft.py", title="Dungeon Draft", url_path="dungeon_draft")
12345676 unmodified lines14151617181918 unmodified lines3839404142434 unmodified lines4849505152537 unmodified lines616263646566139 unmodified lines206207208209210211import streamlit as stimport pandas as pdimport altair as altdef _init_state():if "pt_players" not in st.session_state:6 unmodified linesst.session_state.pt_winning_score = 100if "pt_game_name" not in st.session_state:st.session_state.pt_game_name = ""def _setup_phase():18 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)st.session_state.pt_new_player = ""col1, col2 = st.columns([3, 1])4 unmodified linesst.write("")st.button("Add Player", key="pt_add_btn", on_click=_add_player)if st.session_state.pt_players:st.markdown("**Players:**")for i, p in enumerate(st.session_state.pt_players):7 unmodified linesif st.button("Start Game", type="primary"):st.session_state.pt_game_started = Truest.session_state.pt_scores = []st.rerun()else:st.info("Add at least 2 players to start.")139 unmodified linesif st.button("Save Round", type="primary", key=f"pt_save_r{next_round}"):st.session_state.pt_scores.append(round_scores)st.rerun()12345678910116 unmodified lines181920212223242526272829303132333418 unmodified lines5354555657585960614 unmodified lines6667686970717273747576777879808182837 unmodified lines91929394959697139 unmodified lines237238239240241242243244245246247248249250251252253import uuidimport streamlit as stimport pandas as pdimport altair as altimport sheets_backend as sheetsdef _init_state():if "pt_players" not in st.session_state:6 unmodified linesst.session_state.pt_winning_score = 100if "pt_game_name" not in st.session_state:st.session_state.pt_game_name = ""if "pt_session_id" not in st.session_state:st.session_state.pt_session_id = Nonedef _get_workbook():"""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 Noneif "pt_workbook" not in st.session_state:st.session_state.pt_workbook = sheets.get_or_create_user_workbook(st.user.email)return st.session_state.pt_workbookdef _setup_phase():18 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 = ""col1, col2 = st.columns([3, 1])4 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]if remaining:st.caption("Quick-add from your saved players:")qcols = st.columns(min(len(remaining), 6))for i, name in enumerate(remaining):if qcols[i % len(qcols)].button(name, key=f"pt_quickadd_{name}"):st.session_state.pt_players.append(name)st.rerun()if st.session_state.pt_players:st.markdown("**Players:**")for i, p in enumerate(st.session_state.pt_players):7 unmodified linesif st.button("Start Game", type="primary"):st.session_state.pt_game_started = Truest.session_state.pt_scores = []st.session_state.pt_session_id = uuid.uuid4().hexst.rerun()else:st.info("Add at least 2 players to start.")139 unmodified linesif st.button("Save Round", type="primary", key=f"pt_save_r{next_round}"):st.session_state.pt_scores.append(round_scores)wb = _get_workbook()if wb is not None:for player, score in round_scores.items():sheets.record_round(wb,game_name=game_name or "Points Tracker",session_id=st.session_state.pt_session_id,round_number=next_round,player_name=player,score=score,)st.rerun()
123altairpandasstreamlit1234567altairpandasstreamlit>=1.42gspreadgoogle-authAuthlibtomli_w
12345678910111213141516171819202122232425262728293031323334353637383940import osfrom pathlib import Path
import tomli_w
_SECRETS_PATH = Path(".streamlit/secrets.toml")
def ensure_secrets_file() -> None: if _SECRETS_PATH.exists() or "AUTH_CLIENT_ID" not in os.environ: return # local dev already has the real file; skip if env unset
_SECRETS_PATH.parent.mkdir(exist_ok=True) data = { "auth": { "redirect_uri": os.environ["AUTH_REDIRECT_URI"], "cookie_secret": os.environ["AUTH_COOKIE_SECRET"], "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", }, "gcp_service_account": { "type": "service_account", "project_id": os.environ["GCP_PROJECT_ID"], "private_key_id": os.environ["GCP_PRIVATE_KEY_ID"], "private_key": os.environ["GCP_PRIVATE_KEY"].replace("\\n", "\n"), "client_email": os.environ["GCP_CLIENT_EMAIL"], "client_id": os.environ["GCP_CLIENT_ID"], "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": os.environ["GCP_CLIENT_X509_CERT_URL"], "universe_domain": "googleapis.com", }, "sheets": { "index_spreadsheet_id": os.environ["SHEETS_INDEX_ID"], "shared_folder_id": os.environ.get("SHEETS_SHARED_FOLDER_ID", ""), }, } _SECRETS_PATH.write_text(tomli_w.dumps(data))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import uuidfrom datetime import datetime, timezone
import gspreadimport streamlit as stfrom google.oauth2.service_account import Credentials
_SCOPES = [ "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive",]
_PLAYERS_HEADER = ["player_id", "name", "created_at"]_GAMES_HEADER = ["timestamp", "game_name", "session_id", "round_number", "player_name", "score"]
@st.cache_resourcedef _get_client(): creds = Credentials.from_service_account_info( st.secrets["gcp_service_account"], scopes=_SCOPES ) return gspread.authorize(creds)
def _folder_id(): return st.secrets["sheets"].get("shared_folder_id") or None
def _get_index_ws(): client = _get_client() sh = client.open_by_key(st.secrets["sheets"]["index_spreadsheet_id"]) return sh.worksheet("users")
def get_or_create_user_workbook(email: str) -> gspread.Spreadsheet: client = _get_client() index_ws = _get_index_ws() rows = index_ws.get_all_records() for row in rows: if row.get("email") == email: return client.open_by_key(row["spreadsheet_id"])
sh = client.create(f"BoardGameTracker - {email}", folder_id=_folder_id()) players_ws = sh.sheet1 players_ws.update_title("players") players_ws.append_row(_PLAYERS_HEADER) games_ws = sh.add_worksheet(title="games_played", rows=1, cols=len(_GAMES_HEADER)) games_ws.append_row(_GAMES_HEADER)
try: sh.share(email, perm_type="user", role="writer") except gspread.exceptions.APIError: pass # sharing is a nice-to-have; don't block provisioning on it
index_ws.append_row([email, sh.id, sh.url, datetime.now(timezone.utc).isoformat()]) return sh
def list_players(wb: gspread.Spreadsheet) -> list[dict]: ws = wb.worksheet("players") return ws.get_all_records()
def add_player(wb: gspread.Spreadsheet, name: str) -> str: ws = wb.worksheet("players") existing = ws.get_all_records() for row in existing: if row.get("name", "").strip().lower() == name.strip().lower(): return row["player_id"]
player_id = uuid.uuid4().hex ws.append_row([player_id, name, datetime.now(timezone.utc).isoformat()]) return player_id
def record_round( wb: gspread.Spreadsheet, *, game_name: str, session_id: str, round_number: int, player_name: str, score: int,) -> None: ws = wb.worksheet("games_played") ws.append_row( [ datetime.now(timezone.utc).isoformat(), game_name, session_id, round_number, player_name, score, ] ).gitignoreAdded+7
README.md+49
app.py+18
pages/points_tracker.py+42
requirements.txt+5-1
src/bootstrap_secrets.pyAdded+40
src/sheets_backend.pyAdded+95