import json import streamlit as st from google_auth_oauthlib.flow import Flow SCOPES = [ # lets us see all the calendars that the user can see "https://www.googleapis.com/auth/calendar.readonly", # lets us read the details of the events in a calendar "https://www.googleapis.com/auth/calendar.events.readonly", ] @st.cache_resource def get_flow(): """Create the oauth flow client""" client_creds_str = st.secrets.get("GOOGLE_CLIENT_CREDENTIALS") if client_creds_str: client_creds = json.loads(client_creds_str) else: with open("credentials.json", "r") as f: client_creds = json.load(f) flow = Flow.from_client_config( client_creds, scopes=SCOPES, redirect_uri="urn:ietf:wg:oauth:2.0:oob", ) return flow def get_auth_url(flow: Flow) -> str: """Construct the oauth authorization url for the user to visit to authenticate and authorize scopes.""" auth_url, _ = flow.authorization_url(prompt="consent") return auth_url @st.cache_resource def get_creds(_flow: Flow, code: str): """Get the oauth credentials from the authorization code. Cache it.""" _flow.fetch_token(code=code) creds = _flow.credentials st.session_state.creds = creds return creds def load_creds() -> str | None: """Load the oauth credentials from the session state.""" return st.session_state.get("creds", None)