""" pipeline/google_login.py -- Google OAuth login for Gemini API access. Uses google-auth-oauthlib InstalledAppFlow to authenticate via browser. After login, the access token is used directly with the Generative Language REST API so the user NEVER needs to touch an API key manually. Credentials are stored in storage/google_token.json and auto-refreshed. """ from __future__ import annotations import json, time, threading from pathlib import Path from typing import Optional, Tuple # Where we persist the user's OAuth token _TOKEN_FILE = Path(__file__).parent.parent / "storage" / "google_token.json" # Gemini generative language scope _SCOPES = ["https://www.googleapis.com/auth/generative-language"] # -- Bundled OAuth client credentials ----------------------------------------- # These are "Desktop app" / "Installed app" OAuth 2.0 credentials. # They are intentionally public-facing (like VS Code's GitHub OAuth client). # They allow users to log in with Google; they cannot access anything beyond # what the user explicitly authorises. No secrets are exposed. _CLIENT_CONFIG = { "installed": { "client_id": "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com", "client_secret": "d-FL95Q19q7MQmFpd7hHD0Ty", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"], } } # -- Core OAuth helpers -------------------------------------------------------- def _load_token() -> Optional[dict]: if _TOKEN_FILE.exists(): try: return json.loads(_TOKEN_FILE.read_text(encoding="utf-8")) except Exception: pass return None def _save_token(token_data: dict): _TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True) _TOKEN_FILE.write_text(json.dumps(token_data, indent=2), encoding="utf-8") def _refresh_token(token_data: dict) -> Tuple[bool, dict]: """Use the refresh_token to get a new access_token.""" try: import requests r = requests.post( _CLIENT_CONFIG["installed"]["token_uri"], data={ "client_id": _CLIENT_CONFIG["installed"]["client_id"], "client_secret": _CLIENT_CONFIG["installed"]["client_secret"], "refresh_token": token_data.get("refresh_token", ""), "grant_type": "refresh_token", }, timeout=15, ) resp = r.json() if "access_token" in resp: token_data["access_token"] = resp["access_token"] token_data["expires_at"] = time.time() + resp.get("expires_in", 3600) _save_token(token_data) return True, token_data return False, token_data except Exception as e: return False, token_data def get_valid_token() -> Optional[str]: """Return a valid access_token, refreshing if needed. None if not logged in.""" token_data = _load_token() if not token_data: return None if time.time() > token_data.get("expires_at", 0) - 60: ok, token_data = _refresh_token(token_data) if not ok: return None return token_data.get("access_token") def is_logged_in() -> bool: return get_valid_token() is not None def logout(): if _TOKEN_FILE.exists(): _TOKEN_FILE.unlink() # -- Browser login flow -------------------------------------------------------- def login_with_browser(log_fn=None) -> Tuple[bool, str]: """ Launch Google OAuth in the default browser. Blocks until auth completes or fails. Returns (success, message). """ def log(m): if log_fn: log_fn(m) try: from google_auth_oauthlib.flow import InstalledAppFlow except ImportError: return False, ( "google-auth-oauthlib not installed.\n" "Run: pip install google-auth-oauthlib" ) try: log("Opening browser for Google login...") flow = InstalledAppFlow.from_client_config(_CLIENT_CONFIG, scopes=_SCOPES) # Try local server first (most reliable), fallback to console input try: creds = flow.run_local_server(port=0, open_browser=True) except Exception: creds = flow.run_console() token_data = { "access_token": creds.token, "refresh_token": creds.refresh_token, "expires_at": creds.expiry.timestamp() if creds.expiry else time.time() + 3600, } _save_token(token_data) log("[OK] Google login successful -- token saved") return True, "Logged in successfully [OK]" except Exception as e: return False, f"Login failed: {e}" # -- Gemini call via REST (no API key needed when using OAuth token) ----------- def gemini_generate_oauth(prompt: str, model: str = "gemini-2.0-flash") -> str: """Call Gemini API using the stored OAuth token (no API key).""" token = get_valid_token() if not token: raise RuntimeError("Not logged in to Google. Please sign in via Settings.") try: import requests url = (f"https://generativelanguage.googleapis.com/v1beta/models/" f"{model}:generateContent") headers = { "Authorization": f"Bearer {token}", "Content-Type": "application/json", } body = { "contents": [{"parts": [{"text": prompt}]}], "generationConfig": {"temperature": 0.2, "maxOutputTokens": 1024}, } r = requests.post(url, headers=headers, json=body, timeout=60) r.raise_for_status() candidates = r.json().get("candidates", []) if candidates: parts = candidates[0].get("content", {}).get("parts", []) if parts: return parts[0].get("text", "").strip() return "[No response from Gemini]" except Exception as e: raise RuntimeError(f"Gemini OAuth call failed: {e}") # -- Quick validity check ------------------------------------------------------ def validate_google_login() -> Tuple[bool, str]: """Test if the stored Google token works with Gemini.""" token = get_valid_token() if not token: return False, "Not signed in. Click 'Sign in with Google'." try: result = gemini_generate_oauth("Reply with the single word: OK", model="gemini-2.0-flash") if "OK" in result or len(result) > 0: return True, "Google login active -- Gemini working [OK]" return True, "Google login active [OK]" except Exception as e: return False, f"Token expired or invalid: {e}"