mongodb - 密码未经过哈希处理并保存在数据库中
问题描述
我使用库 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,
})
}
解决方案
如果我在您的“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();
})
推荐阅读
- python - TypeError:Update_Profile() 缺少 1 个必需的位置参数:'self'
- java - 自动生成 CHANGELOG.md 文件
- trace32 - Trace32 - PBI=MCIServer 非法逗号错误
- c - 实现一个名为翻转的函数;它将一个数字作为输入并翻转它的最后 N 个数字
- c++ - Sqlite3 C++ 数据库被锁定
- java - 如何将 MySQL 数据库注入项目文件夹
- arrays - 如何在 swift 中一次在 Firestore 文档中设置多个字段
- java - 在 setOnEditCommit JavaFX 之后禁用 TableCell
- r - Jtools-错误消息-没有适用于“summ”的方法应用于类“list”的对象
- android - Android 自定义 SeekBar - 进度不跟随拇指