import { google } from "googleapis";
import { OAuth2Client } from "google-auth-library";
import { authenticate } from "@google-cloud/local-auth";
import fs from "fs/promises";
import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const credentialsPath = "../secrets/google-credentials.json";
const tokenPath = "../secrets/token.json";
const CREDENTIALS_PATH = path.join(__dirname, credentialsPath);
const TOKEN_PATH = path.join(__dirname, tokenPath);
const SCOPES = [
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.compose",
];
async function getAuthClient(): Promise<OAuth2Client> {
// Try to load existing token first
try {
const tokenRaw = await fs.readFile(TOKEN_PATH, "utf-8");
const tokens = JSON.parse(tokenRaw);
// Create client with saved tokens
const credentialsRaw = await fs.readFile(CREDENTIALS_PATH, "utf-8");
const { installed } = JSON.parse(credentialsRaw);
const client = new google.auth.OAuth2(
installed.client_id,
installed.client_secret,
"http://localhost"
);
client.setCredentials(tokens);
return client;
} catch {
// No token found - need to authenticate
throw new Error("Not authenticated. Run authorization flow first.");
}
}
export async function authorizeNewToken() {
const auth = await authenticate({
keyfilePath: CREDENTIALS_PATH,
scopes: SCOPES,
});
// Save the tokens for future use
await fs.writeFile(TOKEN_PATH, JSON.stringify(auth.credentials, null, 2));
return auth as unknown as OAuth2Client;
}
export { getAuthClient };