Passport local strategy req.isAuthenticated() is always false

Viewed 82

I am trying to setup a login for my new app with passport but I am having some difficulties, no matter what I do req.isAuthenticated() is always false. I have tried reordering the middleware as suggested in some other responses to other such questions, but that didn't help, and it already was in the supposedly correct order. Morgan output:

POST /login 302 80.428 ms - 23
GET / 302 0.573 ms - 28
GET /login 200 0.544 ms - 12

Here is my code:

const passport = require("passport")
const initializePassport = require("./passportConfig")
initializePassport(passport)

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
  cors({
    origin: `http://${REACT_ENDPOINT}:${REACT_PORT}`,
    credentials: true,
  })
);
app.use(flash());
app.use(cookieParser("secretcode"));
app.use(
  session({
    cookie: {
      secure: true,
      maxAge: 86400,
      sameSite: "none",
    },
    secret: "secretcode",
    resave: true,
    saveUninitialized: true,
  })
);
app.use(passport.initialize());
app.use(passport.session());

I have tried setting the secure, resave, saveUninitialized to true and to false, no significant difference.

And here is the passportConfig:

function initialize(passport) {
  const authenticateUser = (username, password, done) => {
    User.findOne({ username: username }, async (err, user) => {
      if (err) throw err;
      if (!user) return done(null, false, { message: "No user with that username!" });

      try {
        if (await bcrypt.compare(password, user.password)) {
          console.log(user);
          return done(null, user);
        } else {
          return done(null, false, { message: "Password is incorrect" });
        }
      } catch (e) {
        return done(e);
      }
    });
  };

  passport.use(
    new LocalStrategy(
      {
        usernameField: "username",
        passwordField: "password",
      },
      authenticateUser
    )
  );
  passport.serializeUser(({ id }, done) => {
    User.findById(id, (err, user) => {
      console.log(user);
      done(null, user.id);
    });
  });
  passport.deserializeUser((id, done) => {
    console.log(id);
    User.findOne({ _id: id }, (err, user) => {
      done(null, user);
    });
  });
}

Both console.logs after the bcrypt.compare and within the serializeUser work correctly and return the correct user. However later in my routing:

app.post(
  "/login",
  checkNotAuthenticated,
  passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/login",
    failureFlash: true,
  })
);

app.get("/login", (req, res) => {
  res.send("please login");
});

app.get("/", checkAuthenticated, (req, res) => {
  res.send("logged in");
});

function checkAuthenticated(req, res, next) {
  console.log(req.isAuthenticated());
  if (req.isAuthenticated()) return next();

  res.redirect("/login");
}

Here within checkAuthenticated, req.isAuthenticated() is always false. But serialize and bcrypt.compare give me the correct User.

I have tried using both User.findOne and findById no difference between the two.

User model:

const mongoose = require("mongoose");

const User = new mongoose.Schema({
  username: String,
  password: String,
});

module.exports = mongoose.model("User", User);
0 Answers
Related