Passport / done函数和passReqToCallBack可以一起使用吗?

时间:2016-11-21 09:17:28

标签: javascript passport.js passport-local

您好我使用本地护照,我想用它制定注册策略。

我希望用户为注册提供username-password-firstname-lastname,所以我尝试在我的策略中使用passReqToCallback:true

passport.use('local-signup', new LocalStrategy({
    passReqToCallBack: true
},
(req, username, password, done) => {
    process.nextTick(() => {
        User.findOne({ 'local.username' : username }, (err, user) => {
            if (err) return done(err);
            if (user) return done(null, false, { status: false, details: 'not ok' });
            const newUser = new User();
            newUser.local.username = username;
            newUser.local.password = newUser.generateHash(password);
            newUser.save((err) => {
                if (err) throw err;
                return done(null, newUser);
            });
        })
    });
}))

然后使用req.body.firstname ...以便将其保存在我的bd中。

问题在于:我不能使用passReqToCallback和done函数......

如果你可以帮我解决这个问题,我读到的所有内容都告诉我或设置passReqtoCallBack:如果我想使用req或将其设置为false,如果我已经完成不是函数错误,则为true ....

由于

1 个答案:

答案 0 :(得分:1)

您正在尝试将用户名和密码传递给回调函数,但您尚未在新的LocalStrategy中定义用户名和密码字段,即:

  passport.use('local.signup',new LocalStrategy({
  usernameField: 'email',    **//the usernameField contains the email or the name of the user**
  passwordField: 'password',
  passReqToCallback : true  **//this line states pass request to callback is true**
}, function(req , email , password , done){   //this is callback function and it takes the req as its first argument then email , password and done as its respective arguments.
  req.checkBody('email' , 'Invalid Email').notEmpty().isEmail();
  req.checkBody('password' , 'Invalid password').notEmpty().isLength({min:4});
  var errors = req.validationErrors();
  if (errors) {
    var messages = [];
    errors.forEach(function(error){
      messages.push(error.msg);
    });
    return done(null , false , req.flash('error' , messages));
  }
  User.findOne({email: email}, function(err , user){
    if (err) {
      return done(err);
    }
    if (user) {
      return done(null , false , {message: "Email is all ready in use"});
    }
    if (!user) {
        return done(null, false, { message: 'Incorrect email' });
    }
    var newUser = new User();
    newUser.local.email = email;
    newUser.local.password = newUser.encryptPassword(password);
    newUser.save(function(err){
      if (err)
       throw err;
        return done(null, newUser);
    });
  });
}));

希望这有帮助。