File size: 2,491 Bytes
8ddf321
 
 
 
 
 
 
 
f05338f
8ddf321
 
 
 
 
f05338f
 
 
 
 
 
 
 
 
8ddf321
 
f05338f
 
8ddf321
 
f05338f
 
8ddf321
 
f05338f
 
8ddf321
 
 
 
f05338f
 
8ddf321
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 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', [])