Search code examples
node.jsexpresscookiespassport.js

isAuthenticated() always returns true


I am trying to use Passport, it works perfectly fine for register and login part, but when I close Chrome/Edge and come back I'm still able to view the restricted page. isAuthenticated() returns false only once, and then always returns true. I have tried using different browsers (Chrome/Edge) and the results are same. I'm not sure if its because of the browsers that the cookies aren't being deleted or if something is wrong with my code. If I clear cookies myself then it works, but would really appreciate a second opinion on this, just want to make sure my code is correct, or if I need to add something so that cookies delete themselves after I exit browser.

require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");

const app = express();

app.set("view engine", "ejs");
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);
app.use(express.static("public"));
app.use(
  session({
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: false,
  })
);
app.use(passport.initialize());
app.use(passport.session());

mongoose.connect(process.env.DB_ADDRESS);

const userSchema = mongoose.Schema({
  email: String,
  password: String,
});
userSchema.plugin(passportLocalMongoose);

const User = new mongoose.model("User", userSchema);

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.get("/secrets", (req, res) => {
  if (req.isAuthenticated()) {
    res.render("secrets");
  } else {
    res.redirect("/login");
  }
});

app.post("/register", (req, res) => {
  User.register(
    { username: req.body.username },
    req.body.password,
    function (err, user) {
      if (err) {
        console.log(err.message);
        res.redirect("/register");
      } else {
        passport.authenticate("local")(req, res, function () {
          res.redirect("/secrets");
        });
      }
    }
  );
});

app.post("/login", (req, res) => {
  const user = new User({
    username: req.body.username,
    password: req.body.password,
  });
  req.login(user, function (err) {
    if (err) {
      console.log(err);
    } else {
      passport.authenticate("local")(req, res, function () {
        res.redirect("/secrets");
      });
    }
  });
});

Solution

  • Try setting a maxAge of the cookies in express-session configuration

    app.use(
      session({
        secret: process.env.SECRET,
        resave: false,
        saveUninitialized: false,
        cookie: {
         maxAge: 1000 * 60 * 60 * 24 //expires in 24hrs
      })
    );
    

    Check the documentation regarding express-session and cookies on here.