All files resetPassword.js

100% Statements 26/26
100% Branches 2/2
100% Functions 13/13
100% Lines 25/25
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 66 67 68 69 70 71 72 73      1x 1x                     1x 24x   24x   24x       1x 40x   40x 40x   32x         56x 56x 56x   56x   56x     96x 32x 4x           4x         28x           28x 28x       32x 32x      
 
/* eslint-env node */
 
const errors = require('feathers-errors');
const debug = require('debug')('authManagement:resetPassword');
 
const {
  getUserData,
  ensureObjPropsValid,
  ensureValuesAreStrings,
  sanitizeUserForClient,
  hashPassword,
  notifier
} = require('./helpers');
 
module.exports.resetPwdWithLongToken = function (options, resetToken, password) {
  return Promise.resolve()
    .then(() => {
      ensureValuesAreStrings(resetToken, password);
 
      return resetPassword(options, { resetToken }, { resetToken }, password);
    });
};
 
module.exports.resetPwdWithShortToken = function (options, resetShortToken, identifyUser, password) {
  return Promise.resolve()
    .then(() => {
      ensureValuesAreStrings(resetShortToken, password);
      ensureObjPropsValid(identifyUser, options.identifyUserProps);
 
      return resetPassword(options, identifyUser, { resetShortToken }, password);
    });
};
 
function resetPassword (options, query, tokens, password) {
  debug('resetPassword', query, tokens, password);
  const users = options.app.service(options.service);
  const usersIdName = users.id;
 
  return Promise.all([
    users.find({ query })
      .then(data => getUserData(data, ['isVerified', 'resetNotExpired'])),
    hashPassword(options.app, password)
  ])
    .then(([user, hashedPassword]) => {
      if (!Object.keys(tokens).every(key => tokens[key] === user[key])) {
        return patchUser(user, {
          resetToken: null,
          resetShortToken: null,
          resetExpires: null
        })
          .then(() => {
            throw new errors.BadRequest('Invalid token. Get for a new one. (authManagement)',
              { errors: { $className: 'badParam' } });
          });
      }
 
      return patchUser(user, {
        password: hashedPassword,
        resetToken: null,
        resetShortToken: null,
        resetExpires: null
      })
        .then(user1 => notifier(options.notifier, 'resetPwd', user1))
        .then(user1 => sanitizeUserForClient(user1));
    });
 
  function patchUser (user, patchToUser) {
    return users.patch(user[usersIdName], patchToUser, {}) // needs users from closure
      .then(() => Object.assign(user, patchToUser));
  }
}