【发布时间】:2017-08-19 11:47:45
【问题描述】:
我正在使用 Postman 测试我正在为一个项目开发的 API。我正在发送
{
"fullName": "Smellydog",
"emailAddress": "SmellydogCoding@gmail.com",
"password": "password",
"confirmPassword": "password"
}
作为此 API 路由的请求正文
users.post('/', (req, res, next) => {
let user = new Users(req.body);
user.save((error,user) => {
if (error) {
return next(error);
} else {
res.status = 201;
res.location('/');
res.end();
}
});
});
这是我的用户架构
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const UserSchema = new mongoose.Schema({
fullName: {
type: String,
required: true,
trim: true,
},
emailAddress: {
type: String,
required: true,
unique: true,
match: [emailRegex, "Please enter a valid email address"],
trim: true
},
password: {
type: String,
required: true
},
confirmPassword: {
type: String,
required: true
}
});
// hash password before saving to database
UserSchema.pre('save', function(next) {
bcrypt.hash(this.password, 10, function(error, hash) {
if (error) {
return next(error);
} else {
this.password = hash;
this.confirmPassword = hash;
next();
}
});
});
UserSchema.pre('validate', function(next) {
let user = this;
if (user.password !== user.confirmPassword) {
return next('Passwords must match');
} else {
next();
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
pre save hook 应该是对密码进行加密,然后将其保存到 password 和 confirmPassword 字段中。如果我使用 Chrome 调试器在预保存挂钩(调用 next() 的位置)的末尾设置断点,并检查 this.password 和 this.confirmPassword,我看到它们被设置为新创建的哈希,但是当之后我检查数据库,这两个字段都设置为原始密码字符串
{
"_id": "58d835f0d026194610578c74",
"fullName": "Smellydog",
"emailAddress": "SmellydogCoding@gmail.com",
"password": "password",
"confirmPassword": "password",
"__v": 0
}
【问题讨论】:
-
您是否尝试过记录第二个“this.password”?我认为上下文发生了变化,与您调用的第一个不同。
-
当我在 this.password 和 this.confirmPassword 上执行 console.log 时(就在 next() 之前),它会输出散列密码:$2a$10$EZD1zuECinDfdQLxvTGjhe8mgCV8Kn7Eprssev5967A0Qch75xE3K 数据库仍将其存储为纯文本
-
你应该在设置它等于哈希之前记录它!它应该返回解密的密码,否则您将哈希设置为新变量。尝试使用箭头函数来保持外部函数的相同上下文。