Here is code implementing Passport authentication with a Google Strategy. It uses Mongoose to store and retrieve user data.
You might need to be familiar with both of these technologies to review this code if not check out the two links I provided.
I have included only the Passport file. I was told I am not using promises correctly and would like to rectify this if it is in fact true.
The code is full of comments below. Please let me know if more clarification or context is needed.
Thanks for any feedback.
Passport
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const DBM = require('../../database/mongoose');
const helper = require('../../config/helper');
// review this post
// https://stackoverflow.com/questions/50339887/can-i-reduce-this-passport-code
// configure Passport to use Google Auth
passport.use('google', new GoogleStrategy(helper.getPassport(), getOrCreateUser));
// passed to passport, this is the starting point for Google Auth
function getOrCreateUser (accessToken, refreshToken, profile, done) {
// abstracts out relevant information from what Google returns
const user_props = obtainProps(profile);
DBM.getUser(user_props.id_google).then( (res) => {
// res[0] will be "true" if the user exists
return res[0] ? done(null, user_props) : createUser(done, user_props);
}).catch( error => {
return done(error, null);
});
}
// the user was not found, create the user
function createUser (done, user_props) {
DBM.createUser(user_props).then(() => {
return done(null, user_props);
}).catch( error => {
return done(error, null);
});
}
// serializeUser required by passport to identify the user uniquely on the client
passport.serializeUser( (profile, done) => {
done(null, profile.id_google);
});
// deserializeUser required by passport to retrieve data on the server using unique
// identifier created by serializeUser
passport.deserializeUser( (id_google, done) => {
DBM.getUser(id_google).then((res) => {
done(null, res[0]);
}).catch( (error) => {
console.error('DBM.getUser() Error: ', error);
});
});
// takes a profile from Google and extracts parameters to save
function obtainProps (profile) {
let props = {};
props.id_google = profile.id;
props.email = profile.emails[0].value;
props.name = profile.displayName;
props.pic_url = profile.photos[0].value;
props.type = profile._json.objectType;
return props;
}
module.exports = passport;