setup-gmail-oauth.js•1.72 kB
// setup-gmail-oauth.js
// Run this once to set up Gmail OAuth
import 'dotenv/config';
import { google } from 'googleapis';
import readline from 'readline';
import fs from 'fs';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const oAuth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
process.env.GOOGLE_REDIRECT || 'http://localhost:3000/oauth2/callback'
);
const SCOPES = [
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/gmail.modify',
];
console.log('Gmail OAuth Setup');
console.log('=================\n');
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
prompt: 'consent'
});
console.log('1. Visit this URL in your browser:');
console.log(' ' + authUrl);
console.log('\n2. After authorizing, you\'ll be redirected to a URL that looks like:');
console.log(' http://localhost:3000/oauth2/callback?code=XXXXX\n');
rl.question('3. Paste the entire redirect URL here: ', async (url) => {
try {
const urlObj = new URL(url);
const code = urlObj.searchParams.get('code');
if (!code) {
throw new Error('No code found in URL');
}
const { tokens } = await oAuth2Client.getToken(code);
if (!fs.existsSync('./data')) {
fs.mkdirSync('./data');
}
fs.writeFileSync('./data/gmail_token.json', JSON.stringify(tokens, null, 2));
console.log('\n✅ Success! Gmail tokens saved to ./data/gmail_token.json');
console.log('You can now run: node gmail-worker.js');
} catch (error) {
console.error('\n❌ Error:', error.message);
}
rl.close();
});