2017-08-30 33 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!'}); 
     }); 
    }); 
});