Search code examples
node.jsexpresspassport.jspassport-local

IsAuthenticated not working as a function using nodejs with passport-local


I'm a begginer with node js and I'm trying to check if the user is authenticated after he registers.

I'm using passport, passport-local and passport-local-mongoose to save the user in a mongoDB database.

This is how the user gets registered:

app.post("/register", function (req, res) {
  const username = req.body.username;
  const password = req.body.password;

  User.register({username: username}, password, function (err, user) {
    if (err) {
      console.log(err);
      res.redirect("/register");
    } else {
      passport.authenticate("local")(req, res, function () {
        res.redirect("/drive");
      });
    }
  });

});

And this is how I'm trying to check if the user is authenticated:

app.get("/drive", function (req, res) {
  if (req.isAuthenticated()) {
    res.render("drive");
  } else {
    res.redirect("/login");
  }
});

If I'm using isAuthenticated() as a function call, this logic will not work and I'll always get redirected to the login page, if I'm using isAuthenticated (not a function call), this logic will work.

I don't understand what is the difference between these two (in the passport package context) and why one works and the other doesn't.


Solution

  • Managed to get this fixed, it was a pretty simple problem.

    When I'm declaring my session options:

    app.use(session({
      secret: 'Our little secret.',
      resave: false,
      saveUninitialized: false,
      cookie: {secure: true}
    }))
    

    I'm using cookie: {secure: true}, and since I'm working on a local enviroment with no HTTPS, as soon as I authenticate, I get deauthenticated due to the fact that the cookie that is supposed to be generated can only work under HTTPS.

    Solution is to just set the cookie option to false and call isAuthenticated().