【发布时间】:2020-08-08 22:36:25
【问题描述】:
我正在尝试在 mongodb 中使用 bcrypt 存储在表单中输入的密码的哈希
这是表格
<form action="/register" method="POST">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="fname" ></p><br/>
<label for="lastname">Lastname</label>
<input type="text" name="lastname" ></p><br/>
<label for="email">Email</label>
<input type="email" name="email" ></p><br/>
<label for="">Password</label>
<input type="password" name="password" ></p><br/>
<input type="submit" value="submit">
这是我的猫鼬模式
const userschema = new mongoose.Schema({ // define a schema
fname:{type:String,trim:true},
lname:{type:String,trim:true},
email:{type:String,lowercase:true,trim:true},
pass:{type:String}
});
这是我的 pre 函数,在我的处理程序中调用 save 之前执行
userschema.pre('save',async function(next){
const user=this;
console.log(user); //in this log the user object this is containing plaintext value of password
await bcrypt.hash(user.pass, 8, function(err, hash) {
if(err){throw new Error(err);}
else{
user.pass=hash;
console.log(user); //and in this log the user object is containing hashed value as expected
}
})
next()}
);
这是我在数据库中保存用户的处理程序
app.post("/register",function(req,res){
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(errors.array());
return res.status(400).render("register",{ errors: errors.array() });
}
console.log(req.body); //out of context question but for some reason only firstname and email are visible in req.body object can anybody body explain
const usave=new user({
fname:req.body.firstname,
lname:req.body.lastname,
email:req.body.email,
pass:req.body.password
})
usave.save((err,doc)=>{
if(err){res.send(err);}
else{
res.send("success");}
});
});
当路由被处理时,用户被成功保存,但存储在数据库中的密码没有被散列。
我确实在 schema.pre('save') 函数中创建了 user.pass=hash,但它没有作为散列存储在数据库中,只是作为纯文本存储
谁能告诉我这段代码有什么问题?如何将哈希密码保存到数据库?
【问题讨论】:
标签: node.js database mongodb express mongoose