import asyncio import json import os import sys from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow # Add the backend directory to sys.path backend_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if backend_dir not in sys.path: sys.path.append(backend_dir) from dotenv import load_dotenv # Now import relative to backend root from core.token_storage import token_storage load_dotenv() # Scopes required for the Gmail integration SCOPES = [ 'https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.compose', 'https://www.googleapis.com/auth/gmail.modify' ] import http.server import socketserver import urllib.parse import webbrowser from google_auth_oauthlib.flow import Flow async def reauth_gmail(): print("--- Gmail Re-authentication ---") client_id = os.getenv("GOOGLE_CLIENT_ID") client_secret = os.getenv("GOOGLE_CLIENT_SECRET") if not client_id or not client_secret: print("ERROR: GOOGLE_CLIENT_ID or GOOGLE_CLIENT_SECRET not found in environment.") return client_config = { "web": { "client_id": client_id, "client_secret": client_secret, "auth_uri": "https://accounts.google.com/o/oauth2/v2/auth", "token_uri": "https://oauth2.googleapis.com/token", } } # Redirect URI must match what's in Google Console redirect_uri = "http://localhost:8080/" flow = Flow.from_client_config( client_config, scopes=SCOPES, redirect_uri=redirect_uri ) auth_url, _ = flow.authorization_url(prompt='consent', access_type='offline') print(f"\n1. Opening browser for Gmail Authorization...") webbrowser.open(auth_url) # Local server to catch the code PORT = 8080 CODE = None class OAuthCallbackHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): nonlocal CODE query = urllib.parse.urlparse(self.path).query params = urllib.parse.parse_qs(query) if "code" in params: CODE = params["code"][0] self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() html = """
Your Gmail account is now successfully linked to Atom. You can close this tab and return to the terminal.