1
votes

I'm having some issues with setting up passport. The information gets to the console.log(req.body) before passport.authenticate and then console.log(req.user) will return undefined afterwards. I will not hit the console.log inside of passport.use() function that is after the new LocalStrategy code. This does not though an error, nothing seems to happen. It will just enter the second if statement if(!user) and return me the status and error I outlined there. I have been trying to debug this for awhile and alas I'm no longer sure what the deal is.

this is what my auth file looks like

router.post("/login", (req, res, next) => {
  console.log(req.body);
  passport.authenticate("local", function (err, user, info) {
    //console.log(req);
    //console.log(user);
    if (err) {
      //console.log("cp1");
      return res.status(400).json({ errors: err });
    }
    if (!user) {
      return res.status(400).json({ errors: "No user found" });
    }

    req.logIn(user, function (err) {
      console.log("cp1");
      if (err) {
        //console.log("cp3");
        return res.status(400).json({ errors: err });
      }
      return res.status(200).json({ success: `logged in ${user.id}` });
    });
  })(req, res, next);
});

and this is what my passport.js file looks like

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

  passport.deserializeUser((id, done) => {
    User.findById(id, (err, user) => {
      done(null, user);
    });
  });
  passport.use(
    new LocalStrategy((email, password, done) => {
      console.log(`${email}  , ${password}`);
      db.User.findOne({ email: email })
        .then((user) => {
          if (!user) {
          } else {
            if (user.password === password) {
              return done(null, user);
            } else {
              return done(null, false, { message: "Wrong Password" });
            }
          }
        })
        .catch((err) => {
          return done(null, false, { message: err });
        });
    })
  );

  passport.initialize();
  passport.session();
1
Are you not hashing your password? It is a very very bad practice. Check out bcryptjs to hash your password.Aviv Lo
Also ` if (!user) {....}` is not returning anything. That's why it's returning undefined because that's the default. You should have put something like user not found. There is something wrong with storing/retrieving users. Check the database and also the database query response to see if there is any problem.Aviv Lo

1 Answers

-1
votes

There is no such thing as req.user, I suppose you meant req.body.user or req.body.username depending on the JSON you send in the request.

I advice you to look at my repo below where I recently successfuly implemented Passport in Express:

https://github.com/fromb2b/saas