My passport .js configuration looks like this:
const Local = require("passport-local").Strategy; const USMODEL = require("../models/user.js"); passport.serializeUser(function(user, done) { console.log("SERIALIZING USER"); done(null, user.id); }); passport.deserializeUser(function(id, done) { console.log("DESUSER", id); var US = mongoose.model("RegUser", USMODEL); US.findById(id, function(err, user) { done(err, id); }); }); passport.use("local-login", new Local({ usernameField: "email", passwordField: "password", passReqToCallback: true },function(req, email, password, done) { var US = mongoose.model("RegUser", USMODEL); US.findOne({"email": email}, function(err, user){ if(err) throw err; if(!user) return done(null, false); if(!user.validPassword(password)) { console.log("password not valid"); return done(null, false); } return done(null, user); }); }));
I change the mongoose model inside each function because I juggle several collections at a time, and I like to have full control over what happens.
In my router.js file, there are the following paths that use the middleware for the passport:
app.get("/user/login", function(req, res) { res.render("signin"); }); app.post('/user/login', function (req, res){ passport.authenticate('local-login', function(err, user, info){ if (err) return res.redirect("/"); if (!user) return res.redirect('/'); else { req.login(user, function(err) { if (err) return next(err); console.log("Request Login supossedly successful."); return res.redirect('/admin/filter'); }); } })(req, res); });
Which after successful authentication redirects to / admin / filter in the same router that looks like this.
app.get("/admin/filter", isLoggedIn, function(req, res){
Now the admin / filter request goes past middleware called isLoggedIn , which theoretically protects my endpoints. It looks like this:
function isLoggedIn(req, res, next) { console.log("This is the authentication middleware, is req authenticated?"); console.log(req.isAuthenticated()); console.log("Does req.user exist?") console.log(req.user); return next(); }
Now you expect that since I called req.login and I received a redirect to my selection endpoint, the request will be authenticated. This is not true.
Request Login supossedly successful. This is the authentication middleware, is req authenticated? false Does req.user exist? undefined
I can not find the source of my problem. Everything is checked when the strategy is called, as well as the callback and req.login , which theoretically represents the req.user object with the data in it. One weird thing I've observed is that I don't see the passport.deserializeUser() method in action. Ever. But this may be about the problem. The passport definitely uses my strategy and rendering of the user object, but somehow the same object is not included in the request. Do you have any assumptions or ideas about what is happening?