Skip to content

Instantly share code, notes, and snippets.

@dliv
Created February 14, 2017 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dliv/2f720dfc2e2ce88ba14770ebaa7c3ebd to your computer and use it in GitHub Desktop.
Save dliv/2f720dfc2e2ce88ba14770ebaa7c3ebd to your computer and use it in GitHub Desktop.
const bcrypt = require('bcrypt');
const knex = require('knex')(require('../../../knexfile'));
const bookshelf = require('bookshelf')(knex);
const User = bookshelf.Model.extend({
tableName: 'users',
hasTimestamps: true,
setPassword(password) {
if (!(password && typeof password === 'string' && password.trim())) {
return Promise.reject('Invalid password.');
}
return bcrypt.hash(password, 10).then(hash => {
this.set('password_hash', hash);
return this;
});
},
verifyPassword(password) {
if (!(password && typeof password === 'string' && password.trim())) {
return Promise.reject('Invalid password.');
}
return bcrypt.compare(password.trim(), this.get('password_hash'));
},
});
User.add = userReq => {
const username = (userReq || {}).username;
const password = (userReq || {}).password;
const cleanUsername = username && username.toLowerCase().trim();
const cleanPassword = password && password.trim();
if (!(cleanUsername && cleanPassword)) {
return Promise.reject();
}
const user = new User({
username: cleanUsername,
email: userReq.email || null,
cellphone: userReq.cellphone || null,
});
return user
.setPassword(cleanPassword)
.then(updatedUser => updatedUser.save());
};
User.findByUsernameAndPass = (username, password) => {
const cleanUsername = username && username.toLowerCase().trim();
const cleanPassword = password && password.trim();
if (!(cleanUsername && cleanPassword)) {
return Promise.reject();
}
return User
.where('username', cleanUsername)
.fetch()
.then(user => {
if (!user) {
return Promise.reject();
}
return user;
})
.then(user => user
.verifyPassword(cleanPassword)
.then(isPasswordMatch => {
if (!isPasswordMatch) {
return Promise.reject();
}
return user;
})
);
};
module.exports = User;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment