bibibi12345 commited on
Commit
ed723a3
·
1 Parent(s): c4bce18

fixing relogin problem

Browse files
Files changed (1) hide show
  1. src/auth.py +97 -15
src/auth.py CHANGED
@@ -132,24 +132,106 @@ def get_credentials():
132
  # Check for credentials in environment variable (JSON string)
133
  env_creds_json = os.getenv("GEMINI_CREDENTIALS")
134
  if env_creds_json:
 
135
  try:
136
- creds_data = json.loads(env_creds_json)
137
- credentials = Credentials.from_authorized_user_info(creds_data, SCOPES)
138
- credentials_from_env = True # Mark as environment credentials
139
-
140
- # Try to refresh if expired and refresh token exists
141
- if credentials.expired and credentials.refresh_token:
142
- try:
143
- logging.info("Environment credentials expired, attempting refresh...")
144
- credentials.refresh(GoogleAuthRequest())
145
- logging.info("Environment credentials refreshed successfully")
146
- except Exception as refresh_error:
147
- logging.warning(f"Failed to refresh environment credentials: {refresh_error}")
148
- logging.info("Using existing environment credentials despite refresh failure")
149
 
150
- return credentials
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  except Exception as e:
152
- logging.warning(f"Failed to load environment credentials: {e}")
153
  # Fall through to file-based credentials
154
 
155
  # Check for credentials file (CREDENTIAL_FILE now includes GOOGLE_APPLICATION_CREDENTIALS path if set)
 
132
  # Check for credentials in environment variable (JSON string)
133
  env_creds_json = os.getenv("GEMINI_CREDENTIALS")
134
  if env_creds_json:
135
+ # First, check if we have a refresh token - if so, we should always be able to load credentials
136
  try:
137
+ raw_env_creds_data = json.loads(env_creds_json)
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
+ # SAFEGUARD: If refresh_token exists, we should always load credentials successfully
140
+ if "refresh_token" in raw_env_creds_data and raw_env_creds_data["refresh_token"]:
141
+ logging.info("Environment refresh token found - ensuring credentials load successfully")
142
+
143
+ try:
144
+ creds_data = raw_env_creds_data.copy()
145
+
146
+ # Handle different credential formats
147
+ if "access_token" in creds_data and "token" not in creds_data:
148
+ creds_data["token"] = creds_data["access_token"]
149
+
150
+ if "scope" in creds_data and "scopes" not in creds_data:
151
+ creds_data["scopes"] = creds_data["scope"].split()
152
+
153
+ # Handle problematic expiry formats that cause parsing errors
154
+ if "expiry" in creds_data:
155
+ expiry_str = creds_data["expiry"]
156
+ # If expiry has timezone info that causes parsing issues, try to fix it
157
+ if isinstance(expiry_str, str) and ("+00:00" in expiry_str or "Z" in expiry_str):
158
+ try:
159
+ # Try to parse and reformat the expiry to a format Google Credentials can handle
160
+ from datetime import datetime
161
+ if "+00:00" in expiry_str:
162
+ # Handle ISO format with timezone offset
163
+ parsed_expiry = datetime.fromisoformat(expiry_str)
164
+ elif expiry_str.endswith("Z"):
165
+ # Handle ISO format with Z suffix
166
+ parsed_expiry = datetime.fromisoformat(expiry_str.replace('Z', '+00:00'))
167
+ else:
168
+ parsed_expiry = datetime.fromisoformat(expiry_str)
169
+
170
+ # Convert to UTC timestamp format that Google Credentials library expects
171
+ import time
172
+ timestamp = parsed_expiry.timestamp()
173
+ creds_data["expiry"] = datetime.utcfromtimestamp(timestamp).strftime("%Y-%m-%dT%H:%M:%SZ")
174
+ logging.info(f"Converted environment expiry format from '{expiry_str}' to '{creds_data['expiry']}'")
175
+ except Exception as expiry_error:
176
+ logging.warning(f"Could not parse environment expiry format '{expiry_str}': {expiry_error}, removing expiry field")
177
+ # Remove problematic expiry field - credentials will be treated as expired but still loadable
178
+ del creds_data["expiry"]
179
+
180
+ credentials = Credentials.from_authorized_user_info(creds_data, SCOPES)
181
+ credentials_from_env = True # Mark as environment credentials
182
+
183
+ # Try to refresh if expired and refresh token exists
184
+ if credentials.expired and credentials.refresh_token:
185
+ try:
186
+ logging.info("Environment credentials expired, attempting refresh...")
187
+ credentials.refresh(GoogleAuthRequest())
188
+ logging.info("Environment credentials refreshed successfully")
189
+ except Exception as refresh_error:
190
+ logging.warning(f"Failed to refresh environment credentials: {refresh_error}")
191
+ logging.info("Using existing environment credentials despite refresh failure")
192
+ elif not credentials.expired:
193
+ logging.info("Environment credentials are still valid, no refresh needed")
194
+ elif not credentials.refresh_token:
195
+ logging.warning("Environment credentials expired but no refresh token available")
196
+
197
+ return credentials
198
+
199
+ except Exception as parsing_error:
200
+ # SAFEGUARD: Even if parsing fails, try to create minimal credentials with refresh token
201
+ logging.warning(f"Failed to parse environment credentials normally: {parsing_error}")
202
+ logging.info("Attempting to create minimal environment credentials with refresh token")
203
+
204
+ try:
205
+ minimal_creds_data = {
206
+ "client_id": raw_env_creds_data.get("client_id", CLIENT_ID),
207
+ "client_secret": raw_env_creds_data.get("client_secret", CLIENT_SECRET),
208
+ "refresh_token": raw_env_creds_data["refresh_token"],
209
+ "token_uri": "https://oauth2.googleapis.com/token",
210
+ }
211
+
212
+ credentials = Credentials.from_authorized_user_info(minimal_creds_data, SCOPES)
213
+ credentials_from_env = True # Mark as environment credentials
214
+
215
+ # Force refresh since we don't have a valid token
216
+ try:
217
+ logging.info("Refreshing minimal environment credentials...")
218
+ credentials.refresh(GoogleAuthRequest())
219
+ logging.info("Minimal environment credentials refreshed successfully")
220
+ return credentials
221
+ except Exception as refresh_error:
222
+ logging.error(f"Failed to refresh minimal environment credentials: {refresh_error}")
223
+ # Even if refresh fails, return the credentials - they might still work
224
+ return credentials
225
+
226
+ except Exception as minimal_error:
227
+ logging.error(f"Failed to create minimal environment credentials: {minimal_error}")
228
+ # Fall through to file-based credentials
229
+ else:
230
+ logging.warning("No refresh token found in environment credentials")
231
+ # Fall through to file-based credentials
232
+
233
  except Exception as e:
234
+ logging.error(f"Failed to parse environment credentials JSON: {e}")
235
  # Fall through to file-based credentials
236
 
237
  # Check for credentials file (CREDENTIAL_FILE now includes GOOGLE_APPLICATION_CREDENTIALS path if set)