passwd.js 639 B

1234567891011121314151617181920212223242526272829
  1. const Promise = require('bluebird');
  2. const bcrypt = Promise.promisifyAll(require('bcrypt'));
  3. const SALT_WORK_FACTOR = 10;
  4. function throwIfFalsy(errorMsg) {
  5. return value => {
  6. if(! value) {
  7. throw new Error(errorMsg);
  8. }
  9. return value;
  10. };
  11. }
  12. function hashPasswordAsync(password) {
  13. return bcrypt.genSaltAsync(SALT_WORK_FACTOR)
  14. .then(salt => bcrypt.hashAsync(password, salt));
  15. }
  16. function matchPasswordAsync(user, password) {
  17. return bcrypt.compare(password, user.password)
  18. .then(throwIfFalsy('Wrong password'))
  19. .then(() => (user));
  20. }
  21. module.exports = {
  22. hash: hashPasswordAsync,
  23. match: matchPasswordAsync
  24. };