什么是“完成"Passport 策略中的回调函数配置“使用";功能 [英] What is "done" callback function in Passport Strategy Configure "use" function

查看:26
本文介绍了什么是“完成"Passport 策略中的回调函数配置“使用";功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个 node.js 和 express.js 菜鸟.这个问题可能看起来很傻,但我真的很困惑.

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

我正在尝试使用 本地策略身份验证/">护照.如官方文档所示,我们可以通过以下代码来计算这个Local Strategy,

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);
    });
  }
));

我的困惑在于 done 回调函数.当官方文档显示此本地策略用作路由处理程序中的中间件时,无需为此 done 回调传递函数参数.

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('/');
  });

那么,如果我们不提供函数参数,这个done回调函数不是会为null吗?如果不是,那个done回调函数是什么,这个done回调函数会发生什么过程?

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?

推荐答案

done 是一种方法 由策略实现内部调用.

然后,如您所见,它会将您导航到 success/error/fail 方法之一(同样,通过实现.还有更多选择).这些选项中的每一个都可以调用next代码>,其中在您的代码段中如下所示:

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('/');
});

success被调用时,它可以附加用户请求 或执行其他操作,具体取决于您的需要(它会查找您传递给 passport.authenticateoptions).如果您想确定何时调用 next,您应该使用 自定义回调 为您提供更大的灵活性.

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.

这篇关于什么是“完成"Passport 策略中的回调函数配置“使用";功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆