Google OAuth 2.0 Strategy
This feature allows you to set up the Google OAuth 2.0 strategy for Passport. It involves configuring the strategy with your Google client ID, client secret, and callback URL, and defining a function to handle the user profile returned by Google.
const GoogleStrategy = require('passport-google-oauth20').Strategy;
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: 'http://www.example.com/auth/google/callback'
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return done(err, user);
});
}));
Authentication Middleware
This feature demonstrates how to set up routes for initiating Google authentication and handling the callback after authentication. The middleware uses the Google strategy to authenticate users and handle success or failure scenarios.
app.get('/auth/google',
passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/');
});