Full-Stack Web Development with Vue.js and Node

(singke) #1
Building OAuth Strategies with passport.js Chapter 7

The callback we just added is http://127.0.0.1:8081/login/google/return, which


we have to define. The configuration is followed by a function that takes the following four


parameters:


accessToken
refreshToken
profile
cb (callback)

Upon a successful request, our application will get redirected to the profile page, which


we are yet to define.


Adding necessary routes for Google login


Now, let's go ahead and add the necessary routes, when we click on the login button and
when we receive the callback from Google. In the same file, google.js, add the following


routes:


const User = require('../models/User');
const passport = require('passport');
const config = require('./../config/Config');
const Strategy = require('passport-google-oauth20').OAuth2Strategy;

module.exports.controller = (app) => {
// google strategy
passport.use(new Strategy({
clientID: config.GOOGLE_APP_ID,
clientSecret: config.GOOGLE_APP_SECRET,
callbackURL: '/login/google/return',
},
(accessToken, refreshToken, profile, cb) => {
// Handle google login
}));

app.get('/login/google',
passport.authenticate('google', { scope: ['email'] }));

app.get('/login/google/return',
passport.authenticate('google', { failureRedirect: '/login' }),
(req, res) => {
res.redirect('/');
});
};
Free download pdf