105

req.body.username我正在使用passportJS ,我想提供的不仅仅是req.body.password我的身份验证策略(passport-local)。

我有 3 个表单域:username, password, &foo

如何req.body.foo从我的本地策略访问,如下所示:

passport.use(new LocalStrategy(
  {usernameField: 'email'},
    function(email, password, done) {
      User.findOne({ email: email }, function(err, user) {
        if (err) { return done(err); }
        if (!user) {
          return done(null, false, { message: 'Unknown user' });
        }
        if (password != 1212) {
          return done(null, false, { message: 'Invalid password' });
        }
        console.log('I just wanna see foo! ' + req.body.foo); // this fails!
        return done(null, user, aToken);

      });
    }
));

我在我的路由(而不是路由中间件)中调用它,如下所示:

  app.post('/api/auth', function(req, res, next) {
    passport.authenticate('local', {session:false}, function(err, user, token_record) {
      if (err) { return next(err) }
      res.json({access_token:token_record.access_token});
   })(req, res, next);

  });
4

2 回答 2

191

您可以启用一个passReqToCallback选项,如下所示:

passport.use(new LocalStrategy(
  {usernameField: 'email', passReqToCallback: true},
  function(req, email, password, done) {
    // now you can check req.body.foo
  }
));

当 setreq成为验证回调的第一个参数时,您可以根据需要对其进行检查。

于 2012-08-02T19:49:21.593 回答
1

在最常见的情况下,我们需要提供 2 个登录选项

  • 带电子邮件
  • 带手机

很简单,我们可以使用常用的用户名和查询 $ 或通过两个选项,我发布了以下片段,如果有人有同样的问题。

我们也可以使用 'passReqToCallback' 也是最好的选择,谢谢@Jared Hanson

passport.use(new LocalStrategy({
    usernameField: 'username', passReqToCallback: true
}, async (req, username, password, done) => {
    try {
        //find user with email or mobile
        const user = await Users.findOne({ $or: [{ email: username }, { mobile: username }] });

        //if not handle it
        if (!user) {
            return done(null, {
                status: false,
                message: "That e-mail address or mobile doesn't have an associated user account. Are you sure you've registered?"
            });
        }

        //match password
        const isMatch = await user.isValidPassword(password);
        debugger
        if (!isMatch) {
            return done(null, {
                status: false,
                message: "Invalid username and password."
            })
        }

        //otherwise return user
        done(null, {
            status: true,
            data: user
        });
    } catch (error) {
        done(error, {
            status: false,
            message: error
        });
    }
}));
于 2019-06-14T10:18:44.583 回答