【发布时间】:2023-03-12 01:47:02
【问题描述】:
我想重构我的用户架构。这个决定的主要原因是我不想担心密码和盐的生成。所以我想将编码逻辑从预保存处理程序移动到设置器。不幸的是,我无法从 setter 访问对象的其他属性(例如 salt)。
因此,默认使用 salt 不起作用,并且使用 salt 编码密码也不起作用。
我目前的实现是:
var userSchema = new mongoose.Schema({
username: {
type: String,
index: { unique: true, sparse: true },
required: true, lowercase: true, trim: true
},
email: {
type: String,
index: { unique: true, sparse: true },
required: true, lowercase: true, trim: true
},
salt: {
type: String,
select: false
},
password: {
type: String,
select: false
},
plainPassword: {
type: String,
select: false
}
});
// FIXME: password encoding only on change, not always
userSchema.pre('save', function(next) {
// check if a plainPassword was set
if (this.plainPassword !== '') {
// generate salt
crypto.randomBytes(64, function(err, buf) {
if (err) return next(err);
this.salt = buf.toString('base64');
// encode password
crypto.pbkdf2(this.plainPassword, this.salt, 25000, 512, function(err, encodedPassword) {
if (err) return next(err);
this.password = new Buffer(encodedPassword, 'binary').toString('base64');
this.plainPassword = '';
}.bind(this));
}.bind(this));
}
next();
});
// statics
userSchema.methods.hasEqualPassword = function(plainPassword, cb) {
crypto.pbkdf2(plainPassword, this.salt, 25000, 512, function(err, encodedPassword) {
if (err) return next(err);
encodedPassword = new Buffer(encodedPassword, 'binary').toString('base64');
cb((this.password === encodedPassword));
}.bind(this));
}
module.exports = mongoose.model('User', userSchema, 'Users');
有人设法将加密转移到 mongoose setter 中吗?
问候,博多
【问题讨论】:
标签: javascript node.js encryption mongoose