Spaces:
Running
Running
| # File: backend/google_utils.py | |
| from google_auth_oauthlib.flow import Flow | |
| from google.oauth2.credentials import Credentials | |
| from googleapiclient.discovery import build | |
| import json | |
| import os | |
| SCOPES = [ | |
| "https://www.googleapis.com/auth/drive", | |
| "https://www.googleapis.com/auth/userinfo.email", | |
| "https://www.googleapis.com/auth/userinfo.profile", | |
| "openid" | |
| ] | |
| REDIRECT_URI = "https://docusort.vercel.app/google-callback" | |
| def get_google_config(): | |
| """Securely load Google keys from Hugging Face Environment Secrets""" | |
| secret_str = os.getenv("GOOGLE_CLIENT_SECRET_JSON") | |
| if not secret_str: | |
| print("WARNING: GOOGLE_CLIENT_SECRET_JSON not found in environment!") | |
| return None | |
| return json.loads(secret_str) | |
| def get_client_id_from_file(): | |
| config = get_google_config() | |
| return config['web']['client_id'] if config else "MISSING" | |
| def get_client_secret_from_file(): | |
| config = get_google_config() | |
| return config['web']['client_secret'] if config else "MISSING" | |
| def get_google_auth_url(): | |
| config = get_google_config() | |
| flow = Flow.from_client_config(config, scopes=SCOPES, redirect_uri=REDIRECT_URI) | |
| auth_url, _ = flow.authorization_url(prompt='consent', access_type='offline') | |
| return auth_url | |
| def exchange_code_for_token(auth_code): | |
| config = get_google_config() | |
| flow = Flow.from_client_config(config, scopes=SCOPES, redirect_uri=REDIRECT_URI) | |
| flow.fetch_token(code=auth_code) | |
| creds = flow.credentials | |
| service = build('oauth2', 'v2', credentials=creds) | |
| user_info = service.userinfo().get().execute() | |
| return { | |
| "access_token": creds.token, | |
| "refresh_token": creds.refresh_token, | |
| "expiry": creds.expiry, | |
| "email": user_info.get('email') | |
| } | |
| def get_drive_service(access_token, refresh_token, token_uri, client_id, client_secret): | |
| creds = Credentials( | |
| token=access_token, | |
| refresh_token=refresh_token, | |
| token_uri=token_uri, | |
| client_id=client_id, | |
| client_secret=client_secret, | |
| scopes=SCOPES | |
| ) | |
| return build('drive', 'v3', credentials=creds) | |
| def list_files_in_folder(service, folder_id="root"): | |
| query = f"'{folder_id}' in parents and trashed = false" | |
| results = service.files().list( | |
| q=query, | |
| pageSize=100, | |
| fields="nextPageToken, files(id, name, mimeType, iconLink, webViewLink, size, md5Checksum)", | |
| orderBy="folder, name" | |
| ).execute() | |
| return results.get('files', []) |