Allow User.hashPassword/validatePassword to be overridden

See https://github.com/strongloop/loopback/issues/251
This commit is contained in:
Raymond Feng 2014-12-20 15:57:38 -08:00
parent 906aa8bc07
commit b7db9808b2
2 changed files with 58 additions and 2 deletions

View File

@ -453,6 +453,24 @@ module.exports = function(User) {
}
};
/*!
* Hash the plain password
*/
User.hashPassword = function(plain) {
this.validatePassword(plain);
var salt = bcrypt.genSaltSync(this.settings.saltWorkFactor || SALT_WORK_FACTOR);
return bcrypt.hashSync(plain, salt);
};
User.validatePassword = function(plain) {
if (typeof plain === 'string' && plain) {
return true;
}
var err = new Error('Invalid password: ' + plain);
err.statusCode = 422;
throw err;
};
/*!
* Setup an extended user model.
*/
@ -467,8 +485,7 @@ module.exports = function(User) {
this.settings.ttl = DEFAULT_TTL;
UserModel.setter.password = function(plain) {
var salt = bcrypt.genSaltSync(this.constructor.settings.saltWorkFactor || SALT_WORK_FACTOR);
this.$password = bcrypt.hashSync(plain, salt);
this.$password = this.constructor.hashPassword(plain);
};
// Make sure emailVerified is not set by creation

View File

@ -135,6 +135,45 @@ describe('User', function() {
assert(u.password !== 'bar');
});
describe('custom password hash', function() {
var defaultHashPassword;
var defaultValidatePassword;
beforeEach(function() {
defaultHashPassword = User.hashPassword;
defaultValidatePassword = User.defaultValidatePassword;
User.hashPassword = function(plain) {
return plain.toUpperCase();
};
User.validatePassword = function(plain) {
if (!plain || plain.length < 3) {
throw new Error('Password must have at least 3 chars');
}
return true;
};
});
afterEach(function() {
User.hashPassword = defaultHashPassword;
});
it('Reports invalid password', function() {
try {
var u = new User({username: 'foo', password: 'aa'});
assert(false, 'Error should have been thrown');
} catch (e) {
// Ignore
}
});
it('Hashes the given password', function() {
var u = new User({username: 'foo', password: 'bar'});
assert(u.password === 'BAR');
});
});
it('Create a user over REST should remove emailVerified property', function(done) {
request(app)
.post('/users')