4

I'm trying to implement an OAUTH2 server in nodeJS, which allows client app to login users using my website(like login with google and in my case it is amazon alexa, which consumes this API/Client app).
I tried using oauth2orise(https://www.npmjs.com/package/oauth2orize) and referred few links:-


Thanks in Advance.

mahendra
  • 367
  • 5
  • 18

2 Answers2

1

I got a very explanatory answer from this repository.

https://github.com/FrankHassanabad/Oauth2orizeRecipes

thanks.

mahendra
  • 367
  • 5
  • 18
1

You can use passportjs to provide you the oauth 2.0 support. You will need googleClientID and googleClientSecret. Which you can get by registering your application to google developers site

var GoogleStrategy = require('passport-google-oauth20').Strategy;

 const mongoose = require('mongoose');
 const keys = require('./keys');
 const User = mongoose.model('users');

module.exports = function(passport){
  passport.use(
new GoogleStrategy({
  clientID:keys.googleClientID,
  clientSecret:keys.googleClientSecret,
  callbackURL:'/auth/google/callback',
  proxy:true
},(accessToken,refreshToken,profile,done)=>{
//     console.log(accessToken);
//     console.log(profile);
  const image = profile.photos[0].value.substring(0,profile.photos[0].value.indexOf('?'));

  const newUser = {
    googleID:profile.id,
    firstName:profile.name.givenName,
    lastName :profile.name.familyName,
    email:profile.emails[0].value,
    image:image
  }

  //Check for existing user
  User.findOne({
    googleID:profile.id
  }).then(user=>{
    if(user){
      //Return user
      done(null,user);
    }
    else{
      //Create a new user
      new User(newUser)
      .save()
      .then(user=> done(null,user)); 
    }
  })
 })
)

passport.serializeUser(function(user, done) {
done(null, user.id);
});

passport.deserializeUser(function(id, done) {
 User.findById(id, function(err, user) {
   done(err, user);
     });
   });
 }

Dependencies = "passport": "^0.4.0", "passport-google-oauth": "^1.0.0"

This will redirect req. to above code..
const express = require('express');
const router = express.Router();
const passport = require('passport');

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

 router.get('/google/callback', 
   passport.authenticate('google', { failureRedirect: '/' }),
   function(req, res) {
   // Successful authentication, redirect home.
   res.redirect('/dashboard');
  });

   router.get('/verify',(req,res)=>{
   if(req.user){
   console.log(req.user);
  }else{
   console.log('Not Auth');
  }
});

router.get('/logout',(req,res)=>{
   req.logout();
   res.redirect('/');
 })
 module.exports = router;
Rishabh Jain
  • 137
  • 3
  • 10