Spaces:
Sleeping
Sleeping
Commit ·
5be8e7e
1
Parent(s): 2f83d3e
Fix CachedWidgetWarning: don't cache the CookieManager component
Browse filesst.cache_resource froze the component after its first render, so
cookie reads/writes never reflected later changes. Fixed by
constructing exactly one CookieManager per script run in app.py and
threading it into cookie_token_store's functions as a parameter,
rather than each function lazily constructing (and risking a second,
same-keyed) instance internally -- calling
stx.CookieManager(key=...) twice in one run raises DuplicateWidgetID.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Files changed (2)
- app.py+12-9
- src/cookie_token_store.py+18-11
40 unmodified lines4142434445464716 unmodified lines64656667686970717273747576771 unmodified line79808182838485864 unmodified lines919293949596973 unmodified lines1011021031041051061071083 unmodified lines11211311411511611711840 unmodified lines)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:return16 unmodified linesreturnrefresh_token = tokens.get("refresh_token")if refresh_token and "cookies" in st.secrets:cookie_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.1 unmodified lineif not st.user.is_logged_in or _access_token_valid():returnif "cookies" in st.secrets:refresh_token = cookie_token_store.get_refresh_token(st.user.email)if refresh_token:try:tokens = google_oauth.refresh_access_token(4 unmodified lines_store_access_token(tokens)returnexcept Exception:cookie_token_store.delete_refresh_token(st.user.email)state = uuid.uuid4().hexst.session_state["drive_oauth_state"] = state3 unmodified linesst.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:3 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")40 unmodified lines4142434445464716 unmodified lines64656667686970717273747576771 unmodified line79808182838485864 unmodified lines919293949596973 unmodified lines1011021031041051061071081091101113 unmodified lines11511611711811912012140 unmodified lines)def _handle_drive_oauth_callback(cookie_manager) -> None:"""Completes the one-time "Connect Google Drive" exchange, if we're mid-flow."""if not st.user.is_logged_in:return16 unmodified linesreturnrefresh_token = tokens.get("refresh_token")if refresh_token and cookie_manager is not None:cookie_token_store.save_refresh_token(cookie_manager, st.user.email, refresh_token)_store_access_token(tokens)st.query_params.clear()st.rerun()def _ensure_drive_access(cookie_manager) -> 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.1 unmodified lineif not st.user.is_logged_in or _access_token_valid():returnif cookie_manager is not None:refresh_token = cookie_token_store.get_refresh_token(cookie_manager, st.user.email)if refresh_token:try:tokens = google_oauth.refresh_access_token(4 unmodified lines_store_access_token(tokens)returnexcept Exception:cookie_token_store.delete_refresh_token(cookie_manager, st.user.email)state = uuid.uuid4().hexst.session_state["drive_oauth_state"] = state3 unmodified linesst.link_button("Connect Google Drive", authorize_url)# Constructed at most once per script run -- see get_cookie_manager's docstring._cookie_manager = cookie_token_store.get_cookie_manager() if "cookies" in st.secrets else Noneif "auth" in st.secrets:_handle_drive_oauth_callback(_cookie_manager)with st.sidebar:if "auth" not in st.secrets:3 unmodified lineselse:st.caption(f"Logged in as {st.user.email}")st.button("Log out", on_click=st.logout)_ensure_drive_access(_cookie_manager)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")
7 unmodified lines891011121314156 unmodified lines222324252627282930313233343536372 unmodified lines404142434445467 unmodified lines_COOKIE_MAX_AGE_DAYS = 400 # ~ the longest lifetime browsers allow anyway (Chrome caps at 400 days)@st.cache_resourcedef _cookie_manager() -> stx.CookieManager:return stx.CookieManager(key="bgt_cookie_manager")6 unmodified linesreturn "bgt_rt_" + hashlib.sha256(email.encode()).hexdigest()[:16]def save_refresh_token(email: str, refresh_token: str) -> None:encrypted = _fernet().encrypt(refresh_token.encode()).decode()expires_at = datetime.now(timezone.utc) + timedelta(days=_COOKIE_MAX_AGE_DAYS)_cookie_manager().set(_cookie_name(email), encrypted, expires_at=expires_at, key=f"set_{_cookie_name(email)}")def get_refresh_token(email: str) -> str | None:encrypted = _cookie_manager().get(_cookie_name(email))if not encrypted:return Nonetry:2 unmodified linesreturn Nonedef delete_refresh_token(email: str) -> None:name = _cookie_name(email)if _cookie_manager().get(name) is not None:_cookie_manager().delete(name, key=f"delete_{name}")7 unmodified lines8910111213141516171819202122236 unmodified lines3031323334353637383940414243442 unmodified lines474849505152537 unmodified lines_COOKIE_MAX_AGE_DAYS = 400 # ~ the longest lifetime browsers allow anyway (Chrome caps at 400 days)def get_cookie_manager() -> stx.CookieManager:"""Constructs the cookie-sync component.Must be called exactly once per script run (not cached, not called morethan once) -- the underlying component re-renders every rerun to reportthe browser's current cookies back to Python, so caching it (viast.cache_resource or otherwise) freezes it stale, and constructing asecond instance with the same key in the same run raisesDuplicateWidgetID."""return stx.CookieManager(key="bgt_cookie_manager")6 unmodified linesreturn "bgt_rt_" + hashlib.sha256(email.encode()).hexdigest()[:16]def save_refresh_token(cookie_manager: stx.CookieManager, email: str, refresh_token: str) -> None:encrypted = _fernet().encrypt(refresh_token.encode()).decode()expires_at = datetime.now(timezone.utc) + timedelta(days=_COOKIE_MAX_AGE_DAYS)name = _cookie_name(email)cookie_manager.set(name, encrypted, expires_at=expires_at, key=f"set_{name}")def get_refresh_token(cookie_manager: stx.CookieManager, email: str) -> str | None:encrypted = cookie_manager.get(_cookie_name(email))if not encrypted:return Nonetry:2 unmodified linesreturn Nonedef delete_refresh_token(cookie_manager: stx.CookieManager, email: str) -> None:name = _cookie_name(email)if cookie_manager.get(name) is not None:cookie_manager.delete(name, key=f"delete_{name}")
app.py+12-9
src/cookie_token_store.py+18-11