All files / src/methods identity-change.ts

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

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 52 53 54 55 56 57 58 59 60 61 62 63 64 65  1x 1x 1x 1x 1x 1x 1x 1x               1x       1x               16x 16x 16x               16x   16x 16x   16x 16x   16x 16x   4x         12x             12x 12x    
 
import { BadRequest } from '@feathersjs/errors';
import makeDebug from 'debug';
import comparePasswords from '../helpers/compare-passwords';
import ensureObjPropsValid from '../helpers/ensure-obj-props-valid';
import getLongToken from '../helpers/get-long-token';
import getShortToken from '../helpers/get-short-token';
import getUserData from '../helpers/get-user-data';
import notifier from '../helpers/notifier';
 
import type {
  IdentifyUser,
  IdentityChangeOptions,
  SanitizedUser
} from '../types';
 
const debug = makeDebug('authLocalMgnt:identityChange');
 
// TODO: identifyUser
 
export default async function identityChange (
  options: IdentityChangeOptions,
  identifyUser: IdentifyUser,
  password: string,
  changesIdentifyUser: Record<string, unknown>,
  notifierOptions: Record<string, unknown> = {}
): Promise<SanitizedUser> {
  // note this call does not update the authenticated user info in hooks.params.user.
  debug('identityChange', password, changesIdentifyUser);
  const usersService = options.app.service(options.service);
  const usersServiceIdName = usersService.id;
  const {
    delay,
    identifyUserProps,
    longTokenLen,
    shortTokenLen,
    shortTokenDigits,
    passwordField
  } = options;
 
  ensureObjPropsValid(identifyUser, identifyUserProps);
  ensureObjPropsValid(changesIdentifyUser, identifyUserProps);
 
  const users = await usersService.find({ query: identifyUser });
  const user1 = getUserData(users);
 
  try {
    await comparePasswords(password, user1[passwordField] as string);
  } catch (err) {
    throw new BadRequest('Password is incorrect.',
      { errors: { [passwordField]: 'Password is incorrect.', $className: 'badParams' } }
    );
  }
 
  const user2 = await usersService.patch(user1[usersServiceIdName], {
    verifyExpires: Date.now() + delay,
    verifyToken: await getLongToken(longTokenLen),
    verifyShortToken: await getShortToken(shortTokenLen, shortTokenDigits),
    verifyChanges: changesIdentifyUser
  });
 
  const user3 = await notifier(options.notifier, 'identityChange', user2, notifierOptions);
  return options.sanitizeUserForClient(user3);
}