← back to Designer Wallcoverings

DW-Agents/dw-agents/google-drive-service-account-example.ts

99 lines

/**
 * Service Account Implementation for Google Drive
 *
 * To use this instead of OAuth:
 * 1. Create a service account in Google Cloud Console
 * 2. Download the JSON key file
 * 3. Save it as /root/Projects/Designer-Wallcoverings/DW-Agents/google-drive-service-account.json
 * 4. Share your Drive folder with the service account email
 * 5. Replace the Google Drive setup in digital-samples-agent.ts with this code
 */

import { google } from 'googleapis';
import * as fs from 'fs';
import * as path from 'path';

// Path to service account key file
const SERVICE_ACCOUNT_KEY_PATH = path.join(__dirname, 'google-drive-service-account.json');

// Check if service account file exists
function hasServiceAccount(): boolean {
  return fs.existsSync(SERVICE_ACCOUNT_KEY_PATH);
}

// Initialize Google Drive with Service Account
function initDriveWithServiceAccount() {
  if (!hasServiceAccount()) {
    throw new Error(
      'Service account key file not found at: ' + SERVICE_ACCOUNT_KEY_PATH +
      '\n\nPlease create a service account and download the JSON key file.' +
      '\nSee GOOGLE-DRIVE-SETUP.md for instructions.'
    );
  }

  const serviceAccountKey = JSON.parse(
    fs.readFileSync(SERVICE_ACCOUNT_KEY_PATH, 'utf8')
  );

  const auth = new google.auth.GoogleAuth({
    credentials: serviceAccountKey,
    scopes: [
      'https://www.googleapis.com/auth/drive.readonly',
      'https://www.googleapis.com/auth/drive.file',
      'https://www.googleapis.com/auth/drive.metadata.readonly',
    ],
  });

  return google.drive({ version: 'v3', auth });
}

// Initialize Google Drive with OAuth (fallback)
function initDriveWithOAuth() {
  const oauth2Client = new google.auth.OAuth2(
    process.env.GOOGLE_CLIENT_ID,
    process.env.GOOGLE_CLIENT_SECRET,
    'http://localhost'
  );

  oauth2Client.setCredentials({
    refresh_token: process.env.GOOGLE_REFRESH_TOKEN,
  });

  return google.drive({ version: 'v3', auth: oauth2Client });
}

// Auto-detect and initialize the best available method
export function initGoogleDrive() {
  try {
    if (hasServiceAccount()) {
      console.log('✅ Using Google Drive Service Account authentication');
      return initDriveWithServiceAccount();
    } else if (process.env.GOOGLE_REFRESH_TOKEN) {
      console.log('⚠️  Using Google Drive OAuth authentication (consider switching to Service Account)');
      return initDriveWithOAuth();
    } else {
      throw new Error(
        'No Google Drive authentication configured!\n' +
        'Please set up either:\n' +
        '  1. Service Account (recommended) - see GOOGLE-DRIVE-SETUP.md\n' +
        '  2. OAuth tokens in .env file'
      );
    }
  } catch (error: any) {
    console.error('❌ Failed to initialize Google Drive:', error.message);
    throw error;
  }
}

// Export for use in digital-samples-agent.ts
export const drive = initGoogleDrive();

// Example usage:
// import { drive } from './google-drive-service-account-example';
//
// const files = await drive.files.list({
//   q: "name contains 'DIG-'",
//   fields: 'files(id, name, mimeType, size, modifiedTime)',
//   pageSize: 100,
// });