Created
February 14, 2017 18:01
-
-
Save dliv/2f720dfc2e2ce88ba14770ebaa7c3ebd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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