"""
Google OAuth Authentication Module
Handles OAuth 2.0 authentication for Gmail API
"""
import os
import json
from pathlib import Path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
SCOPES = [
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/gmail.send',
'https://www.googleapis.com/auth/gmail.modify'
]
def get_credentials():
"""
Get valid Google OAuth credentials.
Creates new credentials if none exist or refreshes if expired.
"""
creds = None
project_root = Path(__file__).parent.parent
token_path = project_root / 'tokens.json'
credentials_path = project_root / 'credentials.json'
if token_path.exists():
creds = Credentials.from_authorized_user_file(str(token_path), SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
if not credentials_path.exists():
raise FileNotFoundError(
f"credentials.json not found at {credentials_path}. "
"Please download from Google Cloud Console."
)
flow = InstalledAppFlow.from_client_secrets_file(
str(credentials_path), SCOPES
)
creds = flow.run_local_server(port=0)
with open(token_path, 'w') as token:
token.write(creds.to_json())
return creds
def validate_credentials():
"""Validate that credentials are properly configured"""
try:
creds = get_credentials()
return {'success': True, 'message': 'Credentials valid'}
except Exception as error:
return {'success': False, 'error': str(error)}