Search code examples
node.jspassport.jspassport-google-oauthpassport-google-oauth2

facing issue with passport js


I am new to node js and I am trying to make an example for authorization with google passport below is my code:

index.js

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

passport.use(new GoogleStrategy({
      clientID        : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      clientSecret    : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      callbackURL     : "http://localhost/google/login",
      passReqToCallback   : true
  },
  function(accessToken, refreshToken, profile, done) {
    return done(); //this is the issue, I am confused with it's use
  }
));

app.get('/failed', function (req, res) {
  res.send('failed login')
});

app.get('/final', function (req, res) {
  res.send('finally google auth has done')
});

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

app.get('/google/login',
  passport.authenticate('google', { failureRedirect: '/failed' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/final');
  });

app.listen('80', () => {
  console.log('server is running')
})

Finally, My goal is to successful login with google without checking the value from DB as I am just learning it.

node index.js

and then i am opening url: http://localhost/auth/google

my program should run get /final after login with google credential but getting an error that TypeError: done is not a function

I am not getting the use of done() and how can I resolve it.


Solution

  • When you use passReqToCallback : true, you need to change the arguments of the callback function. req needs to be passed too as the first argument of the callback function.

    your callback functions argument should be (req, accessToken, refreshToken, profile, done)

    And that is why you are getting the error :

    done is not a function

    Try this :

    passport.use(new GoogleStrategy({
          clientID        : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
          clientSecret    : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
          callbackURL     : "http://localhost/google/login",
          passReqToCallback   : true
      },
      function(req, accessToken, refreshToken, profile, done) {
        return done(); // it will work now
      }
    ));