47 lines
1.7 KiB
JavaScript
47 lines
1.7 KiB
JavaScript
const fs = require('fs');
|
|
const readline = require('readline');
|
|
const { google } = require('googleapis');
|
|
|
|
// If modifying these scopes, delete token.json.
|
|
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.modify'];
|
|
const TOKEN_PATH = 'token.json';
|
|
|
|
fs.readFile('credentials.json', (err, content) => {
|
|
if (err) return console.log('Error loading credentials.json file. Make sure you downloaded it from Google Cloud Console:', err);
|
|
authorize(JSON.parse(content), getNewToken);
|
|
});
|
|
|
|
function authorize(credentials, callback) {
|
|
const {client_secret, client_id, redirect_uris} = credentials.installed || credentials.web;
|
|
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0] || 'urn:ietf:wg:oauth:2.0:oob');
|
|
|
|
fs.readFile(TOKEN_PATH, (err, token) => {
|
|
if (err) return callback(oAuth2Client);
|
|
oAuth2Client.setCredentials(JSON.parse(token));
|
|
console.log("Token already exists and is valid. You don't need to authenticate again.");
|
|
});
|
|
}
|
|
|
|
function getNewToken(oAuth2Client) {
|
|
const authUrl = oAuth2Client.generateAuthUrl({
|
|
access_type: 'offline',
|
|
scope: SCOPES,
|
|
});
|
|
console.log('Authorize this app by visiting this url:', authUrl);
|
|
const rl = readline.createInterface({
|
|
input: process.stdin,
|
|
output: process.stdout,
|
|
});
|
|
rl.question('Enter the code from that page here: ', (code) => {
|
|
rl.close();
|
|
oAuth2Client.getToken(code, (err, token) => {
|
|
if (err) return console.error('Error retrieving access token', err);
|
|
oAuth2Client.setCredentials(token);
|
|
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
|
|
if (err) return console.error(err);
|
|
console.log('Token stored to', TOKEN_PATH);
|
|
});
|
|
});
|
|
});
|
|
}
|