All files / src/methods password-change.ts

100% Statements 23/23
100% Branches 1/1
100% Functions 1/1
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  1x 1x 1x 1x 1x 1x 1x 1x               1x   1x             4x 4x 4x   4x 4x   4x 4x   4x 4x   1x         3x       3x 3x    
 
import { BadRequest } from '@feathersjs/errors';
import makeDebug from 'debug';
import comparePasswords from '../helpers/compare-passwords';
import ensureObjPropsValid from '../helpers/ensure-obj-props-valid';
import ensureValuesAreStrings from '../helpers/ensure-values-are-strings';
import getUserData from '../helpers/get-user-data';
import hashPassword from '../helpers/hash-password';
import notifier from '../helpers/notifier';
 
import type {
  IdentifyUser,
  PasswordChangeOptions,
  SanitizedUser
} from '../types';
 
const debug = makeDebug('authLocalMgnt:passwordChange');
 
export default async function passwordChange (
  options: PasswordChangeOptions,
  identifyUser: IdentifyUser,
  oldPassword: string,
  password: string,
  notifierOptions = {}
): Promise<SanitizedUser> {
  debug('passwordChange', oldPassword, password);
  const usersService = options.app.service(options.service);
  const usersServiceIdName = usersService.id;
 
  ensureValuesAreStrings(oldPassword, password);
  ensureObjPropsValid(identifyUser, options.identifyUserProps);
 
  const users = await usersService.find({ query: identifyUser });
  const user1 = getUserData(users);
 
  try {
    await comparePasswords(oldPassword, user1.password);
  } catch (err) {
    throw new BadRequest('Current password is incorrect.', {
      errors: { oldPassword: 'Current password is incorrect.' }
    });
  }
 
  const user2 = await usersService.patch(user1[usersServiceIdName], {
    password: await hashPassword(options.app, password, options.passwordField)
  });
 
  const user3 = await notifier(options.notifier, 'passwordChange', user2, notifierOptions);
  return options.sanitizeUserForClient(user3);
}