2017-08-30 28 views
0

我正在使用下面的代码;Passport-Local在Mongoose.save中的问题

router.post('/register', function(req, res) { 
     User.register(new User({ username : req.body.username }), 
      req.body.password, function(err, user) { 
      if (err) { 
       return res.status(500).json({err: err}); 

     } 
     if(req.body.firstname) { 
     user.firstname = req.body.firstname; 
     } 

     if(req.body.lastname) { 
     user.lastname = req.body.lastname; 
     } 

     user.save(function(err, user) { 
     passport.authenticate('local')(req, res, function() { 
      return res.status(200).json({status: 'Registration Successful!'}); 
     }); 
     }); 
    }); 
}); 

它产生以下;

{ 
     "_id" : ObjectId("59a631ff29e0a506c81032b3"), 
     "salt" : null, 
     "hash" : null, 
     "username" : "admin", 
     "admin" : false, 
     "lastname" : "Last", 
     "firstname" : "Test", 
     "__v" : 0 
} 

salt和hash是从passport.authenticate('local')生成的。如果我排除user.save(function(err,user){...});代码围绕passport.authenticate,它不更新姓氏或名字部分,但盐和哈希DO得到更新。

我搜索了这个论坛的类似问题;审查护照(http://passportjs.org/docs)和护照本地github(https://github.com/jaredhanson/passport-local)寻求可能的解决方案,但没有找到类似的问题或解决方案。

任何建议都会很棒。

+0

附录:Passport.authenticate返回401在user.save(function(err,user){...})内部时未经授权。 – Mavethel

回答

0

经过大量研究,下面是一个代码示例,可以解决我遇到的问题。名字,姓氏,盐和哈希用它更新得当。

我仍然不确定为什么原始代码在调用user.save中的passport.authenticate时会抛出401/Unauthorized错误。

router.post('/register', function(req, res) { 
    User.register(new User({ 
          username : req.body.username, 
          firstname : req.body.firstname, 
          lastname : req.body.lastname, 
          }), 
     req.body.password, function(err, user) { 
     if (err) { 
      return res.status(500).json({err: err}); 
     } 
     passport.authenticate('local')(req, res, function() { 
      return res.status(200).json({status: 'Registration Successful!'}); 
     }); 
    }); 
});