import os
from pathlib import Path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# Scopes: read + compose draft
SCOPES = [
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.compose",
"https://www.googleapis.com/auth/documents.readonly",
]
# Paths in your project root (directory of this file)
PROJECT_ROOT = Path(__file__).resolve().parent
CREDENTIALS_PATH = Path(
os.environ.get(
"GMAIL_CREDENTIALS_PATH",
PROJECT_ROOT / "credentials.json",
)
)
TOKEN_PATH = PROJECT_ROOT / "token.json"
def get_google_credentials():
"""
Return valid Google OAuth credentials, using token.json and credentials.json.
"""
creds = None
# 1) Try to load saved credentials
if TOKEN_PATH.exists():
creds = Credentials.from_authorized_user_file(str(TOKEN_PATH), SCOPES)
# 2) If no valid creds, either refresh or run the browser flow
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
# Refresh existing token
creds.refresh(Request())
else:
# No token yet: do interactive OAuth flow once
flow = InstalledAppFlow.from_client_secrets_file(
str(CREDENTIALS_PATH),
SCOPES,
)
creds = flow.run_local_server(port=0)
# 3) Save the creds for next time
with TOKEN_PATH.open("w") as token_file:
token_file.write(creds.to_json())
return creds
def get_gmail_service():
"""
Create an authenticated Gmail API service using OAuth.
"""
creds = get_google_credentials()
service = build("gmail", "v1", credentials=creds)
return service
def get_docs_service():
"""
Create an authenticated Google Docs API service using OAuth.
"""
creds = get_google_credentials()
service = build("docs", "v1", credentials=creds)
return service