首页 > 解决方案 > 密码未经过哈希处理并保存在数据库中

问题描述

我使用库 bcryptjs 进行注册系统。bcryptjs 正在工作并对密码进行哈希处理。但它不会将散列密码保存在 mongo db 中。

用户模式

const UserSchema = new Schema({
    name: String,
    email: {
        type: String,
        unique: true,
        match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,]
    },
    password: String
})

UserSchema.methods.generateJwtFromUser = function(){
    const { JWT_SECRET_KEY, JWT_EXPIRE } = process.env;
    const payload = {
        id: this._id,
        name: this.name
    }
    const token = jwt.sign(payload, JWT_SECRET_KEY, {
        expiresIn: JWT_EXPIRE
    })

    return token;
}

UserSchema.pre("save", function(next){
    bcrypt.genSalt(10, (err,salt) => {
        if(err) next(err);
        bcrypt.hash(this.password, salt, (err,hash) => {
            if(err) next(err);
            this.password = hash;
            next();
        })
    })
    next();
})

注册控制器

const register = asyncErrorWrapper(async (req,res) => {
    const infos = req.body;

    const user = await User.create({
        ...infos
    });

    sendJwtToClient(user, res);
})

sendJwtToClient 函数

const sendJwtToClient = (user,res) => {
   const token = user.generateJwtFromUser();

   return res.status(200).json({ 
        success: true,
   })
}

标签: mongodbexpressmongoosebcryptpassword-encryption

解决方案


如果我在您的“UserSchema”中没有错,我没有看到任何用于将密码存储到数据库中的密码选项。

你可以试试这个:

UserSchema.methods.generateJwtFromUser = function(){
    const { JWT_SECRET_KEY, JWT_EXPIRE } = process.env;
    const payload = {
        id: this._id,
        name: this.name,
        password: this.password

    }
    const token = jwt.sign(payload, JWT_SECRET_KEY, {
        expiresIn: JWT_EXPIRE
    })

    return token;
}

UserSchema.pre("save", function(next){
    bcrypt.genSalt(10, (err,salt) => {
        if(err) next(err);
        bcrypt.hash(this.password, salt, (err,hash) => {
            if(err) next(err);
            this.password = hash;
            next();
        })
    })
    next();
})

推荐阅读