Alakbarli commited on
Commit
a9262e4
Β·
verified Β·
1 Parent(s): 1790c4a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -47
app.py CHANGED
@@ -50,32 +50,36 @@ from google.oauth2.credentials import Credentials
50
  # Initialize Cookie Manager at the top of main()
51
  cookie_manager = st_tags.CookieManager()
52
 
 
53
  # def authenticate_service():
54
- # """Handles persistent Google OAuth2 flow using Browser Cookies."""
55
 
56
- # # 1. Try to get token from Browser Cookie first
57
- # cookie_token = cookie_manager.get(cookie="google_creds_token")
 
 
 
 
 
 
 
58
 
59
- # if cookie_token and 'google_creds' not in st.session_state:
 
60
  # try:
61
  # creds_info = json.loads(cookie_token)
62
  # creds = Credentials.from_authorized_user_info(creds_info, ALL_SCOPES)
63
 
64
- # # If token is expired, refresh it
65
  # if creds and creds.expired and creds.refresh_token:
66
  # creds.refresh(Request())
67
- # # Update the cookie with the refreshed token
68
- # cookie_manager.set("google_creds_token", creds.to_json(), key="set_refresh")
69
 
70
  # st.session_state.google_creds = creds
 
71
  # except Exception as e:
72
- # st.warning("Session expired. Please log in again.")
73
 
74
- # # 2. Check Session State
75
- # if 'google_creds' in st.session_state:
76
- # return st.session_state.google_creds
77
-
78
- # # 3. Standard OAuth Flow if no cookie/session exists
79
  # client_config = json.loads(os.environ.get("GCP_CREDENTIALS"))
80
  # redirect_uri = "https://alakbarli-assistant.hf.space/"
81
 
@@ -90,50 +94,50 @@ cookie_manager = st_tags.CookieManager()
90
  # flow.fetch_token(code=query_params["code"])
91
  # creds = flow.credentials
92
 
93
- # # SAVE TO BOTH: Session and Browser Cookie
94
  # st.session_state.google_creds = creds
95
- # cookie_manager.set("google_creds_token", creds.to_json(), key="set_initial")
96
 
97
  # st.query_params.clear()
98
  # st.rerun()
99
  # else:
 
100
  # auth_url, _ = flow.authorization_url(prompt='consent', access_type='offline')
101
- # st.info("⚠️ No active session found. Please sign in.")
102
  # st.link_button("πŸ”‘ Login with Google", auth_url)
103
  # return None
104
 
105
- # return st.session_state.google_creds
106
-
107
-
108
  def authenticate_service():
109
- """Handles persistent Google OAuth2 flow using Browser Cookies with loading wait."""
110
 
111
- # 1. First, check if it's already in the temporary session
112
- if 'google_creds' in st.session_state:
113
  return st.session_state.google_creds
114
 
115
- # 2. If not in session, wait a moment for the Cookie Manager to load
116
- # This is the "secret sauce" to prevent login prompts on refresh
117
- with st.spinner("Restoring session..."):
118
- time.sleep(0.9) # Small delay for the JS component to sync
119
  cookie_token = cookie_manager.get(cookie="google_creds_token")
120
 
121
- # 3. If cookie found, restore it to session
122
  if cookie_token:
123
  try:
124
  creds_info = json.loads(cookie_token)
125
  creds = Credentials.from_authorized_user_info(creds_info, ALL_SCOPES)
126
 
 
127
  if creds and creds.expired and creds.refresh_token:
128
  creds.refresh(Request())
129
- cookie_manager.set("google_creds_token", creds.to_json(), key="refresh_sync")
130
 
131
  st.session_state.google_creds = creds
132
  return creds
133
  except Exception as e:
134
- st.error(f"Cookie restoration failed: {e}")
 
135
 
136
- # 4. Standard OAuth Flow (Only if no session AND no cookie)
 
137
  client_config = json.loads(os.environ.get("GCP_CREDENTIALS"))
138
  redirect_uri = "https://alakbarli-assistant.hf.space/"
139
 
@@ -143,23 +147,31 @@ def authenticate_service():
143
  redirect_uri=redirect_uri
144
  )
145
 
146
- query_params = st.query_params
147
- if "code" in query_params:
148
- flow.fetch_token(code=query_params["code"])
149
- creds = flow.credentials
150
-
151
- # SAVE PERMANENTLY
152
- st.session_state.google_creds = creds
153
- cookie_manager.set("google_creds_token", creds.to_json(), key="init_save")
154
-
155
- st.query_params.clear()
156
- st.rerun()
157
- else:
158
- # This is where the login button lives
159
- auth_url, _ = flow.authorization_url(prompt='consent', access_type='offline')
160
- st.info("πŸ‘‹ Welcome! Please connect your Google account to continue.")
161
- st.link_button("πŸ”‘ Login with Google", auth_url)
162
- return None
 
 
 
 
 
 
 
 
163
 
164
  # --- CALENDAR OPERATIONS ---
165
  def normalize_event_json(event_data):
 
50
  # Initialize Cookie Manager at the top of main()
51
  cookie_manager = st_tags.CookieManager()
52
 
53
+
54
  # def authenticate_service():
55
+ # """Handles persistent Google OAuth2 flow using Browser Cookies with loading wait."""
56
 
57
+ # # 1. First, check if it's already in the temporary session
58
+ # if 'google_creds' in st.session_state:
59
+ # return st.session_state.google_creds
60
+
61
+ # # 2. If not in session, wait a moment for the Cookie Manager to load
62
+ # # This is the "secret sauce" to prevent login prompts on refresh
63
+ # with st.spinner("Restoring session..."):
64
+ # time.sleep(0.9) # Small delay for the JS component to sync
65
+ # cookie_token = cookie_manager.get(cookie="google_creds_token")
66
 
67
+ # # 3. If cookie found, restore it to session
68
+ # if cookie_token:
69
  # try:
70
  # creds_info = json.loads(cookie_token)
71
  # creds = Credentials.from_authorized_user_info(creds_info, ALL_SCOPES)
72
 
 
73
  # if creds and creds.expired and creds.refresh_token:
74
  # creds.refresh(Request())
75
+ # cookie_manager.set("google_creds_token", creds.to_json(), key="refresh_sync")
 
76
 
77
  # st.session_state.google_creds = creds
78
+ # return creds
79
  # except Exception as e:
80
+ # st.error(f"Cookie restoration failed: {e}")
81
 
82
+ # # 4. Standard OAuth Flow (Only if no session AND no cookie)
 
 
 
 
83
  # client_config = json.loads(os.environ.get("GCP_CREDENTIALS"))
84
  # redirect_uri = "https://alakbarli-assistant.hf.space/"
85
 
 
94
  # flow.fetch_token(code=query_params["code"])
95
  # creds = flow.credentials
96
 
97
+ # # SAVE PERMANENTLY
98
  # st.session_state.google_creds = creds
99
+ # cookie_manager.set("google_creds_token", creds.to_json(), key="init_save")
100
 
101
  # st.query_params.clear()
102
  # st.rerun()
103
  # else:
104
+ # # This is where the login button lives
105
  # auth_url, _ = flow.authorization_url(prompt='consent', access_type='offline')
106
+ # st.info("πŸ‘‹ Welcome! Please connect your Google account to continue.")
107
  # st.link_button("πŸ”‘ Login with Google", auth_url)
108
  # return None
109
 
 
 
 
110
  def authenticate_service():
111
+ """Handles persistent Google OAuth2 flow with fix for InvalidGrantError."""
112
 
113
+ # 1. Check if already in current session memory
114
+ if 'google_creds' in st.session_state and st.session_state.google_creds:
115
  return st.session_state.google_creds
116
 
117
+ # 2. Try to recover from Browser Cookie (Persistence across Refresh)
118
+ # We use a small spinner to wait for the JS cookie component to wake up
119
+ with st.spinner("Checking session..."):
120
+ time.sleep(1.0) # Increased to 1s to be safe on slower connections
121
  cookie_token = cookie_manager.get(cookie="google_creds_token")
122
 
 
123
  if cookie_token:
124
  try:
125
  creds_info = json.loads(cookie_token)
126
  creds = Credentials.from_authorized_user_info(creds_info, ALL_SCOPES)
127
 
128
+ # Auto-refresh token if expired
129
  if creds and creds.expired and creds.refresh_token:
130
  creds.refresh(Request())
131
+ cookie_manager.set("google_creds_token", creds.to_json(), key="sync_refresh")
132
 
133
  st.session_state.google_creds = creds
134
  return creds
135
  except Exception as e:
136
+ # If cookie is corrupt, clear it
137
+ cookie_manager.delete("google_creds_token")
138
 
139
+ # 3. Handle the OAuth Redirect (The "Code" exchange)
140
+ # THIS SECTION FIXES YOUR INVALID_GRANT ERROR
141
  client_config = json.loads(os.environ.get("GCP_CREDENTIALS"))
142
  redirect_uri = "https://alakbarli-assistant.hf.space/"
143
 
 
147
  redirect_uri=redirect_uri
148
  )
149
 
150
+ # Check if 'code' is in the URL
151
+ if "code" in st.query_params:
152
+ try:
153
+ # Exchange the code for a real token
154
+ flow.fetch_token(code=st.query_params["code"])
155
+ creds = flow.credentials
156
+
157
+ # Save to session and cookie
158
+ st.session_state.google_creds = creds
159
+ cookie_manager.set("google_creds_token", creds.to_json(), key="save_new_login")
160
+
161
+ # IMPORTANT: Clear the 'code' from URL and Rerun to prevent double-use
162
+ st.query_params.clear()
163
+ st.rerun()
164
+ except Exception as e:
165
+ # If exchange fails (like on a manual refresh), clear URL and try again
166
+ st.query_params.clear()
167
+ st.rerun()
168
+
169
+ # 4. Show Login Button (If no session and no valid code)
170
+ auth_url, _ = flow.authorization_url(prompt='consent', access_type='offline')
171
+ st.info("πŸ‘‹ Welcome! Please sign in with Google to access your dashboard.")
172
+ st.link_button("πŸ”‘ Login with Google", auth_url)
173
+ return None
174
+
175
 
176
  # --- CALENDAR OPERATIONS ---
177
  def normalize_event_json(event_data):