Node JS, Express Js, Google Authentication, OAuth 2.0

Follow @desiprogrammer_

In this Blog/Code Snippet, we are going to extend our earlier project and will add Google Authentication in that. Hence to catch up with this, consider following this Blog First.

Get Source Code

Getting Google Credentials

Our first concern is to go and grab our Google OAuth Client Id and Secret. You can go to this Link and get these for yourself. For more in-depth visual follow This video Tutorial.

Project Setup

Our project is already set and we have all the needed routes and our user model. We just need install a single dependency for handling Google authentication.


 npm install passport-google-oauth20
                    

Logging In A User

After installing this, we will create a file named googleAuth.js in controller directory.

I have also created another file in my config directory named googleData.js to store my client ID and Secret there.


 // in config/goolgeData.js 
 module.exports.clientId = "<Your Client Id>";
 module.exports.clientSecret = "<Your Client Secret>";
                    

 // in controller/ googleAuth.js
 var GoogleStrategy = require('passport-google-oauth20').Strategy;
 const user = require('../model/user');
 const clientId = require('../config/googleData').clientId;
 const clientSecreT = require('../config/googleData').clientSecret;
 
 module.exports = function(passport) {
     passport.use(new GoogleStrategy({
         clientID : clientId,
         clientSecret : clientSecreT,
         callbackURL : "http://localhost:8000/google/callback"
         // remember to change this when you deploy this site
     }, (accessToken, refreshToken, profile, done) => {
         // logging user email
         console.log(profile.emails[0].value);
         // find if a user exists with this email or not
         user.findOne({ email : profile.emails[0].value }).then((data) => {
             if(data){
                 // user exists
                 // update data
                 // I am skipping the update part
                 return done(null, data);
             }else{
                 // create a user
                 user({
                     username : profile.displayName,
                     email : profile.emails[0].value,
                     googleId : profile.id,
                     password : null,
                     provider : 'google',
                     isVerified : true,
                 }).save(function (err, data) {
                     return done(null, data);
                 })
             }
         });
     }
     ))
     
     // serializeUser and deserializeUser
     passport.serializeUser(function (user, done) {
         done(null, user.id);
     });
 
     passport.deserializeUser(function (id, done) {
         user.findById(id, function (err, user) {
             done(err, user);
         });
     });
 
 }                    

User Logout

User logout is simple as earlier. You can refer the preview blog where we had a /logout , rout e which logs out the user and I have also handled cache issue and protected Routes.

You May Also Like..

Local Email Authentication Using Node

Local email-password authentication in Express JS using Passport JS

Language Icon

Flutter PDF

Create Pdf and Read From Internet, Storage or Asset

Language Icon