Skip to content

Instantly share code, notes, and snippets.

@andreaj8
Last active May 20, 2017 19:55
Show Gist options
  • Save andreaj8/c4856387503da591883930cae8274b57 to your computer and use it in GitHub Desktop.
Save andreaj8/c4856387503da591883930cae8274b57 to your computer and use it in GitHub Desktop.
Gmail Get Auth Token
/*
https://medium.com/@andrea_j24/come-trasformare-le-email-in-richieste-http-84c178480d1f
npm install google-auth-library readline
node gmail_auth.js
*/
var googleAuth = require('google-auth-library');
var readline = require('readline');
// See scopes : https://developers.google.com/gmail/api/auth/scopes
var SCOPES = ["https://mail.google.com/"];
/**
* Create an OAuth2 client with the given credentials
* @param {Object} credentials The authorization client credentials.
*/
function authorize(credentials) {
var clientSecret = "YOUR_clientSecret";
var clientId = "YOUR_clientId";
var redirectUrl = "http://localhost:3000";
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
getNewToken(oauth2Client);
}
/**
* Get new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
console.log("token= " ,token);
});
});
}
// Start
authorize();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment