All files identityChange.js

100% Statements 20/20
100% Branches 2/2
100% Functions 10/10
100% Lines 20/20
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      1x 1x                     1x   16x 16x 16x   16x   16x 16x   16x 16x     16x         4x       48x 12x             12x   12x 12x     12x 12x      
 
/* eslint-env node */
 
const errors = require('feathers-errors');
const debug = require('debug')('authManagement:identityChange');
 
const {
  getLongToken,
  getShortToken,
  ensureObjPropsValid,
  sanitizeUserForClient,
  comparePasswords,
  notifier
} = require('./helpers');
 
module.exports = function identityChange (options, identifyUser, password, changesIdentifyUser) {
  // note this call does not update the authenticated user info in hooks.params.user.
  debug('identityChange', password, changesIdentifyUser);
  const users = options.app.service(options.service);
  const usersIdName = users.id;
 
  return Promise.resolve()
    .then(() => {
      ensureObjPropsValid(identifyUser, options.identifyUserProps);
      ensureObjPropsValid(changesIdentifyUser, options.identifyUserProps);
 
      return users.find({ query: identifyUser })
        .then(data => (Array.isArray(data) ? data[0] : data.data[0]));
    })
 
    .then(user1 => Promise.all([
      user1,
      getLongToken(options.longTokenLen),
      getShortToken(options.shortTokenLen, options.shortTokenDigits),
      comparePasswords(password, user1.password,
        () => new errors.BadRequest('Password is incorrect.',
          { errors: { password: 'Password is incorrect.', $className: 'badParams' } })
      )
    ]))
    .then(([user1, longToken, shortToken]) => {
      const patchToUser = {
        verifyExpires: Date.now() + options.delay,
        verifyToken: longToken,
        verifyShortToken: shortToken,
        verifyChanges: changesIdentifyUser
      };
 
      return patchUser(user1, patchToUser);
    })
    .then(user1 => notifier(options.notifier, 'identityChange', user1, null))
    .then(user1 => sanitizeUserForClient(user1));
 
  function patchUser (user1, patchToUser) {
    return users.patch(user1[usersIdName], patchToUser, {}) // needs users from closure
      .then(() => Object.assign(user1, patchToUser));
  }
};