Skip to main content

How to Login with Google API & store user data in MongoDB using Nodejs , expressJS , MongoDB

// Create a File passport.js 


Before creating passport.js  we must have client id , and client secret- . Get your clientID & Client Secret from Google Developer Account using link https://console.cloud.google.com/apis/credentials/consent?project=vernal-zone-374906  

// Make Oauth constent - UserType - External 



== set/add scope email & profile 




Then in Credential setting create new credentials to get Client Id and Client Secret 



//passport.js

import passport from 'passport';

import GoogleStrategy from 'passport-google-oauth2'

import {Strategy} from 'passport-google-oauth2'

passport.serializeUser((user , done) => {

done(null , user);

})

passport.deserializeUser(function(user, done) {

done(null, user);

});


passport.use(new GoogleStrategy({

clientID:"43989350384-ckjvij697vt7g3kdpg9dqe16k60k248.apps.googleusercontent.com",

clientSecret:"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e", // Your Credentials here.

callbackURL:"http://localhost:3000/auth/callback",

passReqToCallback:true

},

function(request, accessToken, refreshToken, profile, done) {

return done(null, profile);

}

));


//===============================================

//IndexRouter.js 


import './passport.js';

import passport from 'passport';



router.use(passport.initialize());

router.use(passport.session());


// Auth

router.get('/auth' , passport.authenticate('google', { scope:

[ 'email', 'profile' ]

}));


// Auth Callback

  router.get( '/auth/callback',

    passport.authenticate( 'google', {

      successRedirect: '/auth/callback/success',

      failureRedirect: '/auth/callback/failure'

}));


// Success

router.get('/auth/callback/success' , (req , res) => {

      if(!req.user)

    res.redirect('/auth/callback/failure');

      console.log(req.user)

    

      req.session.sunm=req.user.email;

      IndexController. registerGoogleUser(req.user).then((result)=>{

        res.render("userhome",{"sunm":req.session.sunm,"srole":"user","ubal":req.session.ubal}); // create your  own userhome page 

      }).catch((err)=>{

          res.render("login",{"output":"Unable to Login With Google"})

          console.log(err)

      })


});


// failure

router.get('/auth/callback/failure' ,(req,res) => {

res.render("login",{"output":"Google Authentication Failed !!"})

})

//==================================================


IndexController.js 


 registerGoogleUser(userDetails){

    return new Promise((resolve,reject)=>{

       IndexModel.getUsers({"email":userDetails.email}).then((result)=>{

            if(result)
               IndexModel.updateGoogleUserModel(userDetails).then((result)=>{
            resolve(result)
        }).catch((err)=>{
          reject(err)
        })

            else 
            var token = crypto.randomBytes(32).toString("hex");
            userDetails={...userDetails,"_id":_id,"status":0,"role":"user","info":Date(),"token":token,"account":"0"}
             IndexModel.registerGoogleUserModel(userDetails).then((result)=>{
            resolve(result)
        }).catch((err)=>{
          reject(err)
        })
       }).catch((err)=>{

       })
    })
 }

//===============================================================

// IndexModel.js 


import GoogleSchemaModel from '../schema/schema.js';

  registerGoogleUserModel(userDetails)
 {
  return new Promise((resolve,reject)=>{

      var obj = new GoogleSchemaModel(userDetails);
    
    obj.save((err,result)=>{

            err ? reject(err) : resolve(result) ;            
    });
  });  
 }

 

   updateGoogleUserModel(userDetails)
 {
  return new Promise((resolve,reject)=>{

    
    
       GoogleSchemaModel.update({"email":userDetails.email},{"info":Date.now()},(err,result)=>{

              err ? reject(err) : resolve(result);        
        });
  });  
 }

getUsers(condition_obj)
 {
  return new Promise((resolve,reject)=>{
  
    RegisterSchemaModel.findOne(condition_obj,(err,result)=>{
      err ? reject(err) : resolve(result);        
    })    
  }) 
 }

//=======================================================

/shema.js


import mongoose from 'mongoose';
import uniqueValidator from 'mongoose-unique-validator';


const GoogleSchema = mongoose.Schema({},{ strict: false })



GoogleSchema.plugin(uniqueValidator); 

const GoogleSchemaModel = mongoose.model('Google_tmp',GoogleSchema,'register'); 

export default GoogleSchemaModel

//=======================connection.js start==========================
import mongoose from 'mongoose';

const url="mongodb://localhost:27017/vasu1"
mongoose.set('strictQuery',false) 
mongoose.connect(url);
console.log("connected to database.");  
===============================================================

//login.js  

</form>
<a href='/auth'> <img src="../img/google.png" height="60px" width="190px"> </a>
</body>

===================================================================



Comments

Popular posts from this blog

Part 15- What is Repeater (Networking Devices)- Computer Networking- CCNA

Repeater  hello friends i am Vasu Birla and today i am starting new segment of CCNA computer networking  its a Networking Devices. we will discuss every important Devices used in networks. Repeater is a first networking devices. What is Repeater  Repeater is a device that receives signals and re-transmits by amplifying or regenerating signals. Repeater has two port one is for receive signals from previous network and second port is for retransmit signals to the next extended network. Two Port Repeater Repeater is a device which is used to Regenerate or replicate signal (Pichhe se aa rahe signal ko regenerate karke ya amplify karke aage strong signals bhej sakte he) Analog and digital both type of signals can be retransmitted by repeater. Here there is difference between regeneration and amplifying.  Amplification means , received signals will be amplified as it is , whether there are impurities in signals  and Regeneration means repeate...

How to Kill the Process: ( Port Process )

If you are seeing a Error like  -   Error: listen EADDRINUSE: address already in use :::3000   then you can easily kill it by running these commands  Find the Process Using Port 3006 : On Windows   netstat -ano | findstr :3000 On Linux/macOS lsof -i :3000       Terminate the Process :       On Windows taskkill /PID <PID> /F    means       taskkill /PID 17780 /F On Linux/macOS kill -9 <PID>     means kill -9 17780                ==============END ==========  

GitHub Repo Collaboration Work on single project

 =============================================== To collaborate effectively with your friend on the same project, you should use Git branches to manage different lines of development. Here's a step-by-step procedure you can follow to streamline collaboration: 1. Create Separate Branches for Each Developer Create a New Branch for Your Friend: On your local repository, create a new branch for your friend. For example if your friend name is kilvish , if you want to create a branch named kilvish , you would run: make sure you would be on main branch already   command->  git checkout -b kilvish git push origin kilvish 2. Set Up Your Friend’s Environment( On your Friend's System )  at kilvish side  run ->  Clone the Repository (if not already done): If your friend hasn’t cloned the repository yet, they should do so: command ->  git clone https://github.com/Vasu-Birla/your-repo.git   // your your main clone line  Fetch All Bran...