All files hash-password.js

69.44% Statements 25/36
66.67% Branches 16/24
71.43% Functions 5/7
69.44% Lines 25/36
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 661x   1x   7x 7x 7x 1x     6x   6x   6x 1x     5x 5x                     5x     5x 2x     3x 3x 3x 3x     3x 3x     3x 3x     3x               3x            
import bcrypt from 'bcryptjs';
 
const defaults = { passwordField: 'password' };
 
export default function (options = {}) {
  return function (hook) {
    if (hook.type !== 'before') {
      throw new Error(`The 'hashPassword' hook should only be used as a 'before' hook.`);
    }
 
    options = Object.assign({}, defaults, hook.app.get('auth'), options);
 
    const crypto = options.bcrypt || bcrypt;
 
    if (hook.data === undefined) {
      return hook;
    }
 
    let password;
    Iif (Array.isArray(hook.data)) {
      // make sure we actually have password fields
      const dataToCheck = [].concat(hook.data);
      dataToCheck.filter(item => {
        return item.hasOwnProperty(options.passwordField);
      });
      if (dataToCheck.length > 0) {
        // set it to the array so we can iterate later on it
        password = hook.data;
      }
    } else {
      password = hook.data[options.passwordField];
    }
 
    if (password === undefined) {
      return hook;
    }
 
    return new Promise(function (resolve, reject) {
      const hash = function (item, password, salt) {
        crypto.hash(password, salt, function (error, hash) {
          Iif (error) {
            return reject(error);
          }
          item[options.passwordField] = hash;
          resolve(hook);
        });
      };
      crypto.genSalt(10, function (error, salt) {
        Iif (error) {
          reject(error);
        }
        Iif (Array.isArray(password)) {
          password.map((item) => {
            if (!item.hasOwnProperty(options.passwordField)) {
              return false;
            }
            hash(item, item[options.passwordField], salt);
          });
        } else {
          hash(hook.data, password, salt);
        }
      });
    });
  };
}