Andrew Moffat commited on
Commit
a93b17b
·
1 Parent(s): 88aba82
Files changed (1) hide show
  1. google_oauth.py +17 -2
google_oauth.py CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  import streamlit as st
2
  from google_auth_oauthlib.flow import Flow
3
 
@@ -9,8 +12,16 @@ SCOPES = [
9
 
10
  @st.cache_resource
11
  def get_flow():
12
- flow = Flow.from_client_secrets_file(
13
- "credentials.json",
 
 
 
 
 
 
 
 
14
  scopes=SCOPES,
15
  redirect_uri="urn:ietf:wg:oauth:2.0:oob",
16
  )
@@ -18,12 +29,15 @@ def get_flow():
18
 
19
 
20
  def get_auth_url(flow: Flow) -> str:
 
 
21
  auth_url, _ = flow.authorization_url(prompt="consent")
22
  return auth_url
23
 
24
 
25
  @st.cache_resource
26
  def get_creds(_flow: Flow, code: str):
 
27
  _flow.fetch_token(code=code)
28
  creds = _flow.credentials
29
  st.session_state.creds = creds
@@ -31,4 +45,5 @@ def get_creds(_flow: Flow, code: str):
31
 
32
 
33
  def load_creds() -> str | None:
 
34
  return st.session_state.get("creds", None)
 
1
+ import json
2
+ import os
3
+
4
  import streamlit as st
5
  from google_auth_oauthlib.flow import Flow
6
 
 
12
 
13
  @st.cache_resource
14
  def get_flow():
15
+ """Create the oauth flow client"""
16
+ client_creds_str = os.getenv("GOOGLE_CLIENT_CREDENTIALS")
17
+ if client_creds_str:
18
+ client_creds = json.loads(client_creds_str)
19
+ else:
20
+ with open("credentials.json", "r") as f:
21
+ client_creds = json.load(f)
22
+
23
+ flow = Flow.from_client_config(
24
+ client_creds,
25
  scopes=SCOPES,
26
  redirect_uri="urn:ietf:wg:oauth:2.0:oob",
27
  )
 
29
 
30
 
31
  def get_auth_url(flow: Flow) -> str:
32
+ """Construct the oauth authorization url for the user to visit to
33
+ authenticate and authorize scopes."""
34
  auth_url, _ = flow.authorization_url(prompt="consent")
35
  return auth_url
36
 
37
 
38
  @st.cache_resource
39
  def get_creds(_flow: Flow, code: str):
40
+ """Get the oauth credentials from the authorization code. Cache it."""
41
  _flow.fetch_token(code=code)
42
  creds = _flow.credentials
43
  st.session_state.creds = creds
 
45
 
46
 
47
  def load_creds() -> str | None:
48
+ """Load the oauth credentials from the session state."""
49
  return st.session_state.get("creds", None)