Skip to content

Instantly share code, notes, and snippets.

@hamptonmoore
Last active May 18, 2019 08:31
Show Gist options
  • Save hamptonmoore/3caeec95ed4febe8c82c83997ec6a4cc to your computer and use it in GitHub Desktop.
Save hamptonmoore/3caeec95ed4febe8c82c83997ec6a4cc to your computer and use it in GitHub Desktop.
Simple NodeJS Module to get the email of oAuth
var { google } = require("googleapis");
var googleConfig = {
clientId: "clientId", // e.g. asdfghjkljhgfdsghjk.apps.googleusercontent.com
clientSecret: "clientSecret", // e.g. _ASDFA%DFASDFASDFASD#FAD-
redirect: "redirectURL" // this must match your google api settings
};
var scopes = ["https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email"];
var oauth2Client = new google.auth.OAuth2(googleConfig.clientId, googleConfig.clientSecret, googleConfig.redirect);
function getGooglePlusApi(auth) {
return google.plus({ version: "v1", auth });
}
function createConnection() {
return new google.auth.OAuth2(googleConfig.clientId, googleConfig.clientSecret, googleConfig.redirect);
}
var oauth = {};
oauth.loginUrl = function() {
return oauth2Client.generateAuthUrl({
// 'online' (default) or 'offline' (gets refresh_token)
access_type: "offline",
// If you only need one scope you can pass it as a string
scope: scopes
});
};
oauth.getUserData = async function(code) {
var auth = createConnection();
var data = await auth.getToken(code);
var tokens = data.tokens;
auth.setCredentials(tokens);
var plus = getGooglePlusApi(auth);
var me = await plus.people.get({ userId: "me" });
var userGoogleId = me.data.id;
var userGoogleEmail = me.data.emails && me.data.emails.length && me.data.emails[0].value;
return {
id: userGoogleId,
email: userGoogleEmail,
tokens: tokens
};
};
module.exports = oauth;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment