gpt4 book ai didi

node.js - 使用 NodeJs Mongo 和 Express 保留更新时的哈希密码

转载 作者:太空宇宙 更新时间:2023-11-04 00:06:59 25 4
gpt4 key购买 nike

我正在尝试使用 MEAN 构建应用程序。注册时,一切正常,用户将被引入数据库,其中字段密码和验证散列。但在更新时,密码和验证将不再被散列,它们将以纯文本形式添加到数据库中。我该如何解决这个问题? (我还没有前端代码,我使用Postman发送请求)

这就是我现在所拥有的:

模型.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');

var schema = new Schema({
firstname: { type: String, required: true },
lastname: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
verify: { type: String, required: true },
});

schema.pre('save', function (next) {
var user = this;
bcrypt.hash(user.password, 10, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
user.verify = hash;
next();
});
});

module.exports = mongoose.model('User', schema);

Controller .js

var router = express.Router();

// register user
router.post('/register', function (req, res, next) {
addToDB(req, res);
});

async function addToDB(req, res) {
var user = new User({
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
password: req.body.password,
verify: req.body.verify
});

try {
doc = await user.save();
return res.status(201).json(doc);
}
catch (err) {
return res.status(501).json(err);
}
}

// update user
router.put('/:id', function (req, res, next) {
User.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) {
console.log('Error in user update: ' + JSON.stringify(err, undefined, 2));
return next(err);
}
res.json(post);
});
});

最佳答案

更新您的 Mongoose 中间件,仅在密码已被修改(或新)时才对密码进行哈希处理,例如

schema.pre('save',  function(next) {
var user = this;

// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();

// generate a salt
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);

// hash the password along with our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);

// override the cleartext password with the hashed one
user.password = hash;
user.verify = hash
next();
});
});
});

因为 findByIdAndUpdatefindOneAndUpdate 的包装器,最好使用 save 以便调用预保存 Hook

var _ = require('lodash');

// update user
router.put('/:id', function (req, res, next) {
// fetch user
User.findById(req.params.id, function(err, post) {
if (err) return next(err);

_.assign(post, req.body); // update user
post.save(function(err) {
if (err) return next(err);
return res.json(200, post);
})
});
});

关于node.js - 使用 NodeJs Mongo 和 Express 保留更新时的哈希密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51818474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com