Alakbarli commited on
Commit
96e528a
Β·
verified Β·
1 Parent(s): a9262e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -32
app.py CHANGED
@@ -17,6 +17,7 @@ from google_auth_oauthlib.flow import InstalledAppFlow
17
  from googleapiclient.discovery import build
18
  from googleapiclient.errors import HttpError
19
 
 
20
  # --- CONFIGURATION ---
21
  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
22
 
@@ -31,6 +32,9 @@ GMAIL_SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
31
  CALENDAR_SCOPES = ['https://www.googleapis.com/auth/calendar.events']
32
  ALL_SCOPES = GMAIL_SCOPES + CALENDAR_SCOPES
33
 
 
 
 
34
  # --- LLM Client Initialization ---
35
  client = None
36
  if OPENROUTER_API_KEY:
@@ -108,67 +112,65 @@ cookie_manager = st_tags.CookieManager()
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
-
144
- flow = InstalledAppFlow.from_client_config(
145
- client_config,
146
- scopes=ALL_SCOPES,
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
 
 
17
  from googleapiclient.discovery import build
18
  from googleapiclient.errors import HttpError
19
 
20
+
21
  # --- CONFIGURATION ---
22
  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
23
 
 
32
  CALENDAR_SCOPES = ['https://www.googleapis.com/auth/calendar.events']
33
  ALL_SCOPES = GMAIL_SCOPES + CALENDAR_SCOPES
34
 
35
+ if 'cookie_manager' not in st.session_state:
36
+ st.session_state.cookie_manager = st_tags.CookieManager(key="maint_cm")
37
+
38
  # --- LLM Client Initialization ---
39
  client = None
40
  if OPENROUTER_API_KEY:
 
112
  # return None
113
 
114
  def authenticate_service():
115
+ cm = st.session_state.cookie_manager
116
 
117
+ # 1. Check current session memory (Fastest)
118
  if 'google_creds' in st.session_state and st.session_state.google_creds:
119
  return st.session_state.google_creds
120
 
121
+ # 2. Try to recover from Browser Cookie
122
+ cookie_token = cm.get(cookie="google_creds_token")
123
+
124
+ # If cookie not immediately found, wait for JS component to sync
125
+ if cookie_token is None and "code" not in st.query_params:
126
+ with st.spinner("Restoring session..."):
127
+ time.sleep(1.2) # Essential delay for CookieManager
128
+ cookie_token = cm.get(cookie="google_creds_token")
129
 
130
  if cookie_token:
131
  try:
132
  creds_info = json.loads(cookie_token)
133
  creds = Credentials.from_authorized_user_info(creds_info, ALL_SCOPES)
134
 
 
135
  if creds and creds.expired and creds.refresh_token:
136
  creds.refresh(Request())
137
+ cm.set("google_creds_token", creds.to_json(), key="sync_refresh")
138
 
139
  st.session_state.google_creds = creds
140
  return creds
141
+ except Exception:
142
+ cm.delete("google_creds_token")
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
+ # 3. Handle OAuth Redirect (Code Exchange)
145
  if "code" in st.query_params:
146
  try:
147
+ client_config = json.loads(GCP_CREDENTIALS_STR)
148
+ flow = InstalledAppFlow.from_client_config(
149
+ client_config,
150
+ scopes=ALL_SCOPES,
151
+ redirect_uri="https://alakbarli-assistant.hf.space/"
152
+ )
153
  flow.fetch_token(code=st.query_params["code"])
154
  creds = flow.credentials
155
 
 
156
  st.session_state.google_creds = creds
157
+ cm.set("google_creds_token", creds.to_json(), key="save_new_login")
158
 
 
159
  st.query_params.clear()
160
  st.rerun()
161
+ except Exception:
 
162
  st.query_params.clear()
163
  st.rerun()
164
 
165
+ # 4. Show Login Button if all above fails
166
+ client_config = json.loads(GCP_CREDENTIALS_STR)
167
+ flow = InstalledAppFlow.from_client_config(
168
+ client_config,
169
+ scopes=ALL_SCOPES,
170
+ redirect_uri="https://alakbarli-assistant.hf.space/"
171
+ )
172
  auth_url, _ = flow.authorization_url(prompt='consent', access_type='offline')
173
+ st.info("πŸ‘‹ Welcome! Please sign in to continue.")
174
  st.link_button("πŸ”‘ Login with Google", auth_url)
175
  return None
176