All files / src index.js

100% Statements 19/19
100% Branches 2/2
100% Functions 8/8
100% Lines 17/17
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36    1x 1x 1x     4x 3x   3x 3x       2x       2x 2x 2x 2x 2x         1x 1x 1x 1x        
import Promise from 'bluebird';
 
const bcrypt = Promise.promisifyAll(require('bcryptjs'));
const crypto = Promise.promisifyAll(require('crypto'));
const SALT_WORK_FACTOR = 10;
 
export function hash(user) {
  if (!user.password) throw new Error('No password provided');
  return bcrypt
      .genSaltAsync(SALT_WORK_FACTOR)
      .then(salt => bcrypt.hashAsync(user.password, salt))
      .then(hash => user.password = hash);
}
 
export function compare(user, password) {
  return bcrypt.compareAsync(password, user.password);
}
 
export function reset(user) {
  return crypto.randomBytesAsync(20).then(buffer => {
    const token = buffer.toString('hex');
    user.resetPasswordToken = token;
    user.resetPasswordExpires = Date.now() + 3600000;
    return token;
  });
}
 
export function update(user, password) {
  user.password = password;
  user.resetPasswordToken = undefined;
  user.resetPasswordExpires = undefined;
  return hash(user).then(() => user);
}
 
export default {hash, compare, reset, update};