Building OAuth Strategies with passport.js Chapter 7
In the preceding code, we have added two routes. If you remember, in Login.vue, we
have added a link to http://localhost:8081/login/google, which will be served by
the first route that we defined here.
Also, if you recall, in the configuration setting, we have added a callback function, which
will be served by the second route that we have defined here as well.
Now, the final thing to do is to actually log in the user using the strategy. Replace the
contents of google.js with the following:
const User = require('../models/User');
const passport = require('passport');
const config = require('./../config/Config');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
module.exports.controller = (app) => {
// google strategy
passport.use(new GoogleStrategy({
clientID: config.GOOGLE_APP_ID,
clientSecret: config.GOOGLE_APP_SECRET,
callbackURL: '/login/google/return',
},
(accessToken, refreshToken, profile, cb) => {
const email = profile.emails[0].value;
User.getUserByEmail(email, (err, user) => {
if (!user) {
const newUser = new User({
fullname: profile.displayName,
email,
facebookId: profile.id,
});
User.createUser(newUser, (error) => {
if (error) {
// Handle error
}
return cb(null, user);
});
} else {
return cb(null, user);
}
return true;
});
}));
app.get('/login/google',
passport.authenticate('google', { scope: ['email'] }));