【问题标题】:hashing password using brcrpt in "pre"在“pre”中使用 brcrpt 散列密码
【发布时间】: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


    【解决方案1】:
    userschema.pre('save', async function(next) {
        var user = this;
        await bcrypt.hash(user.pass, 8, function(err, hash) {
            if (err) {
                return next(err);
            }
            user.pass = hash;
            next();
        })
    });
    

    上面的代码将实现您在将文档保存到DB 时始终使用hashing 密码的目标,在保存文档之前不会对密码进行哈希处理。

    【讨论】:

    • 我不认为盐是问题,因为我在代码 cmets 中提到了当我 console.log 时哈希密码在用户对象中可见,但它没有作为哈希保存在数据库中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    相关资源
    最近更新 更多