Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

javascript - What is "done" callback function in Passport Strategy Configure "use" function

I'm an node.js and express.js noob. This question may seems silly but I'm really in confusion.

I'm trying to configure Local Strategry authentication by using passport. As shown in the official documentation, we can figure this Local Strategy by the following code,

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));

My confusion is about the done callback function. When the official docs show this local strategy using as a middleware in the route handler, there is no need to pass the function parameter for this done callback.

app.post('/login', 
  passport.authenticate('local'),
  function(req, res) {
    res.redirect('/');
  });

So, isn't this done callback function will be null if we don't provide the function parameter? If not, what is that done callback function and what processes will be happening in this done callback function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

done is a method called internally by the strategy implementation.

Then it navigates you, as you can see, to one of the success / error / fail methods (again, by the implementation. there are more options). Each of these options may calls to the next, where in your snippet code is the following:

function(req, res) {
  res.redirect('/');
});

When success is called, it can attach the user to the request or do other things, depending on your needs (it looks for the options you pass to passport.authenticate). If you want to determine when next will be called, you should use custom callback which gives you more flexibility.

I strongly recommend that you read the source.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...