我使用bcrypt for Node.js来加密密码。我也使用Mongoose来创建MongoDB数据库和用户模型。
但是,当我GET
数据时(使用Postman),明文密码不会更新为密码哈希值。这是我的代码:
user.js的:
const userSchema = new mongoose.Schema({
"email": { type: String, required: true, unique: true, trim: true },
"username": { type: String, required: true, unique: true },
"name": {
"first": String,
"last": String
},
"password": { type: String, required: true },
"created_at": { type: Date, default: Date.now },
"updated_at": { type: String }
})
userSchema.pre("save", function(next) {
var user = this
if (!user.isModified('password')) return callback()
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err)
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err)
user.password = hash
console.log(user.password)
})
})
const currentDate = new Date
user.updated_at = currentDate
next()
})
const User = mongoose.model("users", userSchema)
export default User
发布用户数据:
router.route("/users").post((req, res) => {
let json = {}
const newUser = new User({
username: req.body.username,
email: req.body.email,
name: {
first: req.body.firstName,
last: req.body.lastName
},
password: req.body.password
})
newUser.save((err) => {
if (err) {
json.error = err.message
} else {
json.id = newUser._id
}
res.json(json)
})
})
正如我上面所说,当我获取数据时,密码仍然只是简单的明文而不是哈希,没有错误。当我在函数中使用console.log(user.password)
时,它会给我回哈希。
我刚刚开始学习后端内容(我是前端开发人员),所以您也可以感谢任何建议 - 谢谢!
答案 0 :(得分:0)
经典节点回调搞砸。在生成哈希之前调用next()回调!
presave函数必须是这样的:
userSchema.pre("save", function(next) {
var user = this
if (!user.isModified('password')) return callback()
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err)
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err)
user.password = hash
const currentDate = new Date
user.updated_at = currentDate
next()
})
})
})
答案 1 :(得分:0)
router.post("/", async (req, res) => {
const { error } = validate(req.body);//always always validate the data.validating data func should be in the user model module.
if (error) return res.status(400).send(error.details[0].message);
let user = await User.findOne({ email: req.body.email });//make sure user doesnt exist
if (user) return res.status(400).send("User is already registered");
user = new User({
username: req.body.username,
email: req.body.email,
name: {
first: req.body.firstName,
last: req.body.lastName
},
password: req.body.password
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt);
await user.save();
});