Skip to content

Instantly share code, notes, and snippets.

@bendytree
Created April 8, 2020 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bendytree/e57868232eaf35271f0c83c9a57b1c2c to your computer and use it in GitHub Desktop.
Save bendytree/e57868232eaf35271f0c83c9a57b1c2c to your computer and use it in GitHub Desktop.
// https://joshwright.com/tips/google-authentication-for-nodejs/
import { google } from 'googleapis';
const buildAuth = function () {
return new google.auth.OAuth2(
'0000000000000-xxxxxxxx.apps.googleusercontent.com', // clientId
'XXXXXXXXXXXXXXXXXXX', // clientSecret
'http://localhost:7777/google/callback', // redirect
);
};
app.get('/google/login', async (req, res) => {
const auth = buildAuth();
const url = auth.generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
scope: [
'https://www.googleapis.com/auth/userinfo.email',
'profile',
]
});
res.redirect(url);
});
app.get('/google/callback', async (req, res) => {
// get & set tokens
const { code } = req.query;
const auth = buildAuth();
const { tokens } = await auth.getToken(code);
auth.setCredentials(tokens);
// fetch the user's email
const peopleApi = google.people({version: 'v1', auth}).people;
const me = await peopleApi.get({
resourceName: 'people/me',
personFields: 'emailAddresses',
});
const address = me.data.emailAddresses.find(e => e.metadata.primary);
const email = address && address.value;
// TODO: login with email
res.redirect('/');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment