Justin
Justin

Reputation: 972

PassportJs isAuthenticated not Authenticating

I have PassportJS setup with Google+ Login.

The Google authentication seems to work fine but when I redirect to a page that only an authenticated user should have access to. Passport's isAuthenticated() function always seems to return false

I've seen people mention that you should be able to find the user by console logging: req.session.passport.user but when I console log req.session all I get is:

  sessionID: 'Q5NaeyfnAphOK633tKjiGnbbex0KJj7e',
  session:
   Session {
     cookie:
      { path: '/',
        _expires: null,
        originalMaxAge: null,
        httpOnly: true } },

Google Callback route:

router.get("/google/callback", function(req, res, next) {
    passport.authenticate("google", function(err, user, info) {
        req.session.save(()=>{
            res.redirect("/api/v1/dashboard");
            console.log("after Passport AUTH");
        });
    })(req, res, next);
});

Note: I've added a manual req.session.save() to ensure that the session is being saved.

Dashboard route:

router.get("/", middleware.isLoggedIn , function(req, res) {
    console.log("Request: Get All Dashboard Data!");
    models.PortfolioBalance.findAll({ raw: true }).then(function(
        portfolioBalance
    ) {
        res.render("dashboard/index", { portfoliobalances: portfolioBalance });
    });
});

Middleware module:

module.exports = {
    isLoggedIn: function(req, res, next) {
        console.log("===========================================");
        console.log("isAuthenticated: ", req.isAuthenticated);
        console.log("===========================================");
        if (req.isAuthenticated()) {
            return next();
        }
        console.log("not authenticated");
        res.redirect("/login");
    }
};

Serialise and De-Serialise:

//  used to serialize the user for the session
passport.serializeUser(function(user, done) {
    console.log("SerializeUser:", models.User.userId);
    done(null, user.id);
});

// used to deserialize the user
passport.deserializeUser(function(id, done) {
    console.log("deserializeUser:", models.User.userId);
    models.User.findOne({ where: { userId: id } }).then(function(
        err,
        user
    ) {
        done(err, user);
    });
});

Potential Issue:

Upvotes: 3

Views: 920

Answers (1)

RickyM
RickyM

Reputation: 867

First, you will want to use the authenticate as middleware to protect routes and login.

// put in a separate file and then import where you need it for this example lets say auth.js
module.exports = function (){
    return {
        authenticate: passport.authenticate('google', function (err,user){
            if(err)
                res.redirect('/login');
            if(user)
                res.redirect("/api/v1/dashboard");
        })(req,res);
    }
};

Like if you login you might set it up as so

// where you have your routing
var auth = require('path_to_auth.js')();

router.post('/login', auth.authenticate);

Inside of the google strategy is where you want to search for the user.

// from the passport-google npmjs.com documentation adjust for the actual strategy you use
passport.use(new GoogleStrategy({
    returnURL: 'http://localhost:3000/auth/google/return',
    realm: 'http://localhost:3000/'
  },
  function(identifier, done) {
    User.findByOpenID({ openId: identifier }, function (err, user) {
      return done(err, user);
    });
  }
));

You should also import the user model then serialize and deserialize like so

var User = mongoose.model('User', UserSchema); // adjust to your schema

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

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

Upvotes: 5

Related Questions