Da-123 commited on
Commit
1b36342
Β·
1 Parent(s): 8f7fd07

deployed google auth

Browse files
agentic_implementation/email_mcp_server_oauth.py CHANGED
@@ -12,7 +12,9 @@ import os
12
  from typing import Dict, List
13
  from datetime import datetime, timedelta
14
  from dotenv import load_dotenv
15
-
 
 
16
  # Import OAuth-enabled modules
17
  # from tools import extract_query_info, analyze_emails
18
  from gmail_api_scraper import GmailAPIScraper
@@ -22,6 +24,7 @@ from logger import logger
22
  load_dotenv()
23
 
24
  if not oauth_manager.client_secrets_file.exists():
 
25
  oauth_manager.setup_client_secrets(
26
  os.environ["GOOGLE_CLIENT_ID"],
27
  os.environ["GOOGLE_CLIENT_SECRET"]
@@ -168,7 +171,7 @@ def authenticate_user() -> str:
168
  "instructions": [
169
  "Authentication URL has been generated",
170
  "Please click the link below to authenticate:",
171
- "1. Click the authentication URL",
172
  "2. Sign in with your Google account",
173
  "3. Grant Gmail access permissions",
174
  "4. You'll be redirected back automatically",
@@ -183,17 +186,6 @@ def authenticate_user() -> str:
183
  "message": "Could not start authentication process. Check your OAuth configuration."
184
  }
185
 
186
- # result = {
187
- # "success": False,
188
- # "error": "Authentication failed",
189
- # "message": "Please try again or check your internet connection.",
190
- # "instructions": [
191
- # "Make sure you have internet connection",
192
- # "Ensure you complete the authentication in the browser",
193
- # "Try running 'python setup_oauth.py' if problems persist"
194
- # ]
195
- # }
196
-
197
  return json.dumps(result, indent=2)
198
 
199
  except Exception as e:
@@ -227,7 +219,7 @@ def handle_oauth_callback(auth_code: str) -> str:
227
  </body>
228
  </html>
229
  """
230
-
231
  success = oauth_manager.complete_hf_spaces_auth(auth_code)
232
 
233
  if success:
@@ -779,31 +771,16 @@ demo = gr.TabbedInterface(
779
  title="πŸ“§ Gmail Assistant MCP Server (Multi-Account OAuth)"
780
  )
781
 
 
 
 
 
 
 
 
 
 
 
782
  if __name__ == "__main__":
783
- # Set environment variable to enable MCP server
784
- import os
785
- os.environ["GRADIO_MCP_SERVER"] = "True"
786
-
787
- # Check authentication status on startup
788
- current_account = oauth_manager.get_current_account()
789
- all_accounts = oauth_manager.list_accounts()
790
-
791
- if current_account and oauth_manager.is_authenticated():
792
- print(f"βœ… Currently authenticated as: {current_account}")
793
- if len(all_accounts) > 1:
794
- print(f"πŸ“± {len(all_accounts)} total accounts available: {list(all_accounts.keys())}")
795
- elif all_accounts:
796
- print(f"πŸ“± {len(all_accounts)} stored accounts found: {list(all_accounts.keys())}")
797
- print("⚠️ No current account selected. Use the web interface or Claude to switch accounts.")
798
- else:
799
- print("❌ No authenticated accounts. Users will need to authenticate through the web interface.")
800
- print("πŸ’‘ Or run 'python setup_oauth.py' for initial setup.")
801
-
802
- # Launch the server
803
- demo.launch(share=False)
804
-
805
- print("\nπŸš€ MCP Server is running!")
806
- print("πŸ“ MCP Endpoint: http://localhost:7860/gradio_api/mcp/sse")
807
- print("πŸ“– Copy this URL to your Claude Desktop MCP configuration")
808
- print("\nπŸ”— Web Interface: http://localhost:7860")
809
- print("πŸ“ Use the web interface to authenticate and test the tools")
 
12
  from typing import Dict, List
13
  from datetime import datetime, timedelta
14
  from dotenv import load_dotenv
15
+ from fastapi.responses import HTMLResponse
16
+ from fastapi import FastAPI,Request
17
+ from fastapi.routing import APIRoute
18
  # Import OAuth-enabled modules
19
  # from tools import extract_query_info, analyze_emails
20
  from gmail_api_scraper import GmailAPIScraper
 
24
  load_dotenv()
25
 
26
  if not oauth_manager.client_secrets_file.exists():
27
+ print("Setupy")
28
  oauth_manager.setup_client_secrets(
29
  os.environ["GOOGLE_CLIENT_ID"],
30
  os.environ["GOOGLE_CLIENT_SECRET"]
 
171
  "instructions": [
172
  "Authentication URL has been generated",
173
  "Please click the link below to authenticate:",
174
+ "1. Open the authentication URL(auth_url) in a new browser tab",
175
  "2. Sign in with your Google account",
176
  "3. Grant Gmail access permissions",
177
  "4. You'll be redirected back automatically",
 
186
  "message": "Could not start authentication process. Check your OAuth configuration."
187
  }
188
 
 
 
 
 
 
 
 
 
 
 
 
189
  return json.dumps(result, indent=2)
190
 
191
  except Exception as e:
 
219
  </body>
220
  </html>
221
  """
222
+ print(f"Received OAuth callback with code: {auth_code}")
223
  success = oauth_manager.complete_hf_spaces_auth(auth_code)
224
 
225
  if success:
 
771
  title="πŸ“§ Gmail Assistant MCP Server (Multi-Account OAuth)"
772
  )
773
 
774
+ app = FastAPI()
775
+ # Add your OAuth callback route
776
+ @app.get("/oauth2callback")
777
+ async def google_oauth_cb(request: Request):
778
+ code = request.query_params.get("code")
779
+ print("code:", code)
780
+ return HTMLResponse(handle_oauth_callback(code))
781
+
782
+ app = gr.mount_gradio_app(app, demo, path="/")
783
+
784
  if __name__ == "__main__":
785
+ import uvicorn
786
+ uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
agentic_implementation/oauth_manager.py CHANGED
@@ -195,7 +195,7 @@ class GmailOAuthManager:
195
  scopes=self.SCOPES
196
  )
197
  flow.redirect_uri = self.redirect_uri
198
-
199
  auth_url, _ = flow.authorization_url(
200
  access_type='offline',
201
  include_granted_scopes='true',
@@ -236,7 +236,7 @@ class GmailOAuthManager:
236
 
237
  # Wait for a reasonable time to see if auth completes
238
  # This allows the callback to potentially complete the auth
239
- timeout = 60 # 1 minute for manual completion
240
  start_time = time.time()
241
 
242
  while (time.time() - start_time) < timeout:
@@ -336,11 +336,12 @@ class GmailOAuthManager:
336
 
337
  Returns:
338
  Redirect URI string
339
- """
340
- space_id = os.getenv('SPACE_ID')
341
- space_author = os.getenv('SPACE_AUTHOR', 'username')
342
- return f"https://{space_author}-{space_id}.hf.space/oauth/callback"
343
 
 
344
 
345
  # def authenticate_interactive(self) -> bool:
346
  # """Interactive authentication flow that opens browser
@@ -627,4 +628,4 @@ class GmailOAuthManager:
627
  return self.current_account_email
628
 
629
  # Global OAuth manager instance
630
- oauth_manager = GmailOAuthManager()
 
195
  scopes=self.SCOPES
196
  )
197
  flow.redirect_uri = self.redirect_uri
198
+ print("πŸ‘‰ redirect_uri being sent to Google:", self.redirect_uri, flush=True)
199
  auth_url, _ = flow.authorization_url(
200
  access_type='offline',
201
  include_granted_scopes='true',
 
236
 
237
  # Wait for a reasonable time to see if auth completes
238
  # This allows the callback to potentially complete the auth
239
+ timeout = 10 # 1 minute for manual completion
240
  start_time = time.time()
241
 
242
  while (time.time() - start_time) < timeout:
 
336
 
337
  Returns:
338
  Redirect URI string
339
+ # """
340
+ # space_id = os.getenv('SPACE_ID')
341
+ # space_author = os.getenv('SPACE_AUTHOR', 'username')
342
+ return redirect_uri
343
 
344
+ # For running in a local machine, use this method instead
345
 
346
  # def authenticate_interactive(self) -> bool:
347
  # """Interactive authentication flow that opens browser
 
628
  return self.current_account_email
629
 
630
  # Global OAuth manager instance
631
+ oauth_manager = GmailOAuthManager(credentials_dir="secure_data")
requirements.txt CHANGED
@@ -9,6 +9,8 @@ requests
9
  loguru
10
  python-dateutil
11
 
 
 
12
  # MCP server support
13
  mcp
14
 
 
9
  loguru
10
  python-dateutil
11
 
12
+ uvicorn
13
+
14
  # MCP server support
15
  mcp
16