为什么我的密码没有被哈希?

时间:2018-06-01 02:55:36

标签: express hash passwords bcrypt

使用下面的代码,我可以成功添加新用户。但是,当我查看数据库中的用户时,密码是纯文本。显然,我做错了什么。

let newUser = new User的部分中,密码从请求正文传入。如果没有错误,bcrypt应该散列密码并将newUser.password设置为哈希值,对吗?

//ADD USER Submit POST Route
router.post('/register',
 [
  check('name').isLength({min:1}).trim().withMessage('Name 
required'),
  check('email').isLength({min:1}).trim().withMessage('Email 
required'),
  check('email').isEmail().trim().withMessage('Email is not valid'),
  check('password').isLength({min:1}).withMessage('Password 
required'),
  check('password').custom((value,{req, loc, path}) => {
    if (value !== req.body.password2) {
        // throw error if passwords do not match
        throw new Error("Passwords do not match");
    } else {
        return value;
    }
})
 ],
  (req,res,next)=>{

  let newUser = new User({
  name:req.body.name,
  email:req.body.email,
  username:req.body.username,
  password: req.body.password
 });

 const errors = validationResult(req);

 if (!errors.isEmpty()) {
  console.log(errors);
     res.render('register',
      { 
       newUser:newUser,
       errors: errors.mapped()
      });
   }
   else{
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
            if(err) {
                console.log(err);
            }
            newUser.name = req.body.name;
            newUser.email = req.body.email;
            newUser.username = req.body.username;
            newUser.password = hash;
        })
    })

  newUser.save(err=>{
   if(err)throw err;
   req.flash('success','You are now registered and can log in');
   res.redirect('/users/login');
  });
 }
});

任何建议都将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

newUser.save移到bcrypt.hash回调中。首先命中save,在bcrypt完成并运行回调之前在数据库中创建用户。

同样在bcrypt.hash的回调中,您不需要再次执行以下操作:

newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.username = req.body.username;

请尝试以下操作:

(req,res,next)=>{

  let newUser = new User({
  name:req.body.name,
  email:req.body.email,
  username:req.body.username,
  password: req.body.password
 });

 const errors = validationResult(req);

 if (!errors.isEmpty()) {
  console.log(errors);
     res.render('register',
      { 
       newUser:newUser,
       errors: errors.mapped()
      });
   }
   else{
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
            if(err) {
                console.log(err);
            }
            newUser.password = hash;
            newUser.save(err=>{
               if(err)throw err;
               req.flash('success','You are now registered and can log in');
               res.redirect('/users/login');
            });
        })
    })
 }