mongodb - 无法在平均堆栈中散列密码
问题描述
这是来自路由文件的代码。
router.put('/reset/:token', function(req, res, next) {
console.log('reseting the password');
User.findOne({resetPasswordToken:req.params.token}, function(err, user) {
if(err) {
return next(err);
}
if (!user) {
return res.status(422).json({errors: [{msg: 'invalid reset token'}]});
}
user.resetPasswordToken ='';
user.resetPasswordExpires = '';
user.password = req.body.password;
User.addUser(user, (err, user) => {
if(err){
res.json({success: false, msg:'password has not changed'});
} else {
res.json({success: true, msg:'password has changed'});
}
});
});
});
这部分代码来自我的架构文件。
const UserSchema = mongoose.Schema({
password: {
type: String,
required: true
},
resetPasswordToken: {
type: String
},
resetPasswordExpires: {
type: Date
}
});
const User = module.exports = mongoose.model('User', UserSchema);
module.exports.addUser = function(newUser, callback){
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
newUser.password = hash;
newUser.save(callback);
});
});
}
当我尝试休息密码时,它正在存储,因为我已经给出了输入。它不是对密码进行哈希处理。例如,我将密码指定为“zp12345”,在它存储为的数据库中 "password" : "zp12345".
解决方案
为了解决您需要修复 addUser 方法的问题:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
module.exports.addUser = function(newUser, callback){
bcrypt.hash(newUser.password, bcrypt.genSaltSync(10), null, (err, hash) => {
if (err) {
return next(err);
}
newUser.password = hash;
newUser.save(callback);
})
};
这里还有另一个例子:Mongoose Pre Save Change Password
这是库文档:Bcrypt Nodejs
推荐阅读
- machine-learning - 时间序列二分类
- javascript - 为什么我的 html 只加载我的两个 javascript 脚本之一?
- javascript - 在javascript中旋转图像一个SVG
- sql - 在 Postgresql 中使用 SQL 将数据行透视到标题
- reactjs - 两条相同的反应状态行返回不同的结果
- node.js - 使用 Nodejs 将数据发送到 header.ejs
- python - 我将如何制作一个 linkvertise 包装器
- javascript - 通过读取该数组的长度在数组中创建存储桶
- python - 上限等于 Python 范围内的下限
- javascript - 从 HTML 中的变量中删除空格