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

How to deploy NodeJS app on server with Apache2 and acess it with Server IP addresss - Node JS deploy project Live.

     hello friens , This is Vasu Birla , in previous post we have seen the deployement of NodeJS app on AWS instance server instance but AWS server is expensive than other servers . SO today we will use simple Ubuntu server for making Live out Project using Apache2 . At the end you will be abe to access your NodeJS app using server IP address from anywhere  .. 1.  Login to your server using SSH terminal . (in AWS part i already explained how to do this )     -> Open your putty in hostname put your server IP -      login with ssh username ->root and password     (if you dont have root username and pass ask your      provider or reset it from cpanel or hosting panel ) 2. after login - on terminal you can Put your project anywhere.     There are two ways to put your project folder on server location     (i) - > using Github - (very popular and easy to track your everyday code changes to your project folder)             you can push your entire project folder to git-hub and and

Part 19- Router (Networking Devices)- Computer Networking- CCNA

Hello friends...i am Vasu Birla and today will discuss about the most important Networking Device ..Router.  so let's start... ROUTER Router is a device which connect two or more networks together, which is why router is also known is Inter-networking device also. Inter-networking means two or more networks are connected together with the help of router. one more thing router is just like a computer  but it is designed for routing only, our computer can be router also but that are software router while hardware router which are specialize for routing is more efficient and fast than software router.  There is a Operating System installed on router which get moves data from one network to another network with the help of routing table.  Router does work on Network layer or Layer 3 of the OSI model.  Cisco Router There many companies which manufacture Router but main companies are - Cisco , Juniper , HP, 3com and Nortel  Functions of Router

Part 16- HUB (Networking Devices)- Computer Networking- CCNA

hello friends , Today we will discuss about the second Networking Devices Ethernet HUB. HUB Hub is a centralize device via all devices (computers, printers etc.) are connected with the star topology.  Hub connects other multiple devices together and helps to make connectivity mutually so that they can share and transfer data to each and every devices which is connected to that hub.  Hub does work at the first layer means at Physical layer of the OSI Model. Hub has many ports, and each port works like a repeater so Hub is also known as Multiport Repeater. A Hub Types of Hubs. there are three kind of Hubs. Active , passive and Manageable hubs. 1. Active Hubs - These hubs regenerates and amplify the signals to keep them strong. one more thing there is electricity needed in the active Hubs. 2. Passive Hubs- Passive Hubs simply forward the received signals. this type of hub does not make pure signal or regenerate so  these passive hubs doesn't n