I want to refactor my user schema. The main reason for this decision is that I do not want to worry about password and salt generation. So I would like to move the encoding logic from the pre save handler to a setter. Unfortunately I do not have access from a setter to other properties of the object (like salt).
So defaulting a salt does not work and encoding a password with a salt also not.
My current implementation is:
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');
Has somebody managed to move encryption to mongoose setters?
Regards, bodo
You DO have access to other properties from within the setter with the use of the
thiskeyword. For example:However, setters are unfit for your use case. As you probably know, HMAC-SHA1 is super expensive and therefore will block unless performed asynchronously. Mongoose setters require the function to return a value and there is no way to route the result of crypto.pbkdf2()’s callback to the return value of the setter function. This is a limitation of asynchronous javascript and not Mongoose itself: you can’t wrap an async call within a sync function, as this destroys the nature of the async chain.
Setters are most widely used for simple string manipulations and data sanitization.
Here is a demo for encryption using only instance methods: