const fs = require("fs"); const path = require("path"); const readline = require("readline"); const { google } = require("googleapis"); require("dotenv").config(); const CREDENTIALS_PATH = process.env.GOOGLE_CREDENTIALS || "./credentials.json"; const TOKEN_PATH = process.env.GOOGLE_TOKEN || "./token.json"; function loadCredentials() { const raw = fs.readFileSync(CREDENTIALS_PATH, "utf8"); const json = JSON.parse(raw); const cfg = json.installed || json.web; if (!cfg) throw new Error("Invalid credentials.json. Expected installed/web client."); return { client_id: cfg.client_id, client_secret: cfg.client_secret, redirect_uris: cfg.redirect_uris, }; } async function main() { const { client_id, client_secret, redirect_uris } = loadCredentials(); const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]); const authUrl = oAuth2Client.generateAuthUrl({ access_type: "offline", scope: ["https://www.googleapis.com/auth/drive.file"], prompt: "consent", }); console.log("Authorize this app by visiting this url:\n", authUrl, "\n"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("Paste the code from the page here: ", async (code) => { rl.close(); const { tokens } = await oAuth2Client.getToken(code.trim()); fs.writeFileSync(TOKEN_PATH, JSON.stringify(tokens, null, 2)); console.log("✅ Token stored at:", path.resolve(TOKEN_PATH)); }); } main().catch((e) => { console.error("Auth error:", e); process.exit(1); });