0
votes

I' learning Node.s and Express, and I'm following this example from https://github.com/EvanHahn/Express.js-in-Action-code/tree/master/Chapter_08/learn-about-me. Can you explain the following question?

  1. In the "/login" post route, if I need to access the request and response objects, how should I do it?
  2. What is the "done" function inside LocalStrategy(), and how I know what parameter to pass? Looks like it take 3 arguments, and the 2nd argument is the user object, and the 3rd argument is the message. What is the 1st argument?
  3. How do the username and password get passed from the "/login" post route into LocalStrategy? What magic is behind the scene?
router.post("/login", passport.authenticate("login", {
  successRedirect: "/",
  failureRedirect: "/login",
  failureFlash: true
}));
passport.use("login", new LocalStrategy(function(username, password, done) {
    User.findOne({ username: username }, function(err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: "No user has that username!" });
      }
      user.checkPassword(password, function(err, isMatch) {
        if (err) { return done(err); }
        if (isMatch) {
          return done(null, user);
        } else {
          return done(null, false, { message: "Invalid password." });
        }
      });
    });
  }));
1

1 Answers

1
votes

The answer for question #1 and #2 is at http://passportjs.org/docs

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

3 is at the same docs page.

passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'passwd'
  },
  function(username, password, done) {
    // ...
  }
));