хеширование пароля с использованием brcrpt в "pre" - PullRequest
1 голос
/ 07 августа 2020

я пытаюсь сохранить ha sh пароля, введенного в форму с использованием bcrypt в mongodb

это форма

<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">

это мой mon goose schema

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} 
});

, и это моя предварительная функция, которая должна выполняться перед вызовом 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");}
    });
});

при обработке маршрута пользователь успешно сохраняется, но пароль, хранящийся в базе данных, не хешируется.

Я сделал user.pass = ha sh в schema.pre ('save'), но она не сохраняется в базе данных, поскольку ha sh просто сохраняется как обычный текст

может ли кто-нибудь сказать мне, что не так с этим кодом? как мне сохранить хеш-пароль к базе данных?

1 Ответ

0 голосов
/ 07 августа 2020
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();
    })
});

Приведенный выше код выполнит sh вашу цель всегда hashing пароль при сохранении документа в DB, пароли не хешируются, пока документ не будет сохранен.

...