All files / src/hooks add-verification.ts

95.65% Statements 22/23
100% Branches 8/8
100% Functions 3/3
95.45% Lines 21/22

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 521x 1x 1x 1x 1x 1x                   1x     26x 26x 14x   14x 14x   14x         14x         1x     13x   13x 13x 13x 13x   13x            
import { GeneralError } from '@feathersjs/errors';
import { checkContext } from 'feathers-hooks-common';
import getLongToken from '../helpers/get-long-token';
import getShortToken from '../helpers/get-short-token';
import ensureFieldHasChanged from '../helpers/ensure-field-has-changed';
import { defaultConfigureOptions } from '../configureAuthManagement';
 
import type { HookContext } from '@feathersjs/feathers';
import type { AuthenticationManagementService } from '../services';
 
/**
 *
 * @param [path='authManagement'] the servicePath for your authManagement service
 * @returns
 */
export default function addVerification (
  path?: string
): ((context: HookContext) => Promise<HookContext>) {
  path = path || defaultConfigureOptions.path; // default: 'authManagement'
  return async (context: HookContext): Promise<HookContext> => {
    checkContext(context, 'before', ['create', 'patch', 'update']);
 
    try {
      const { options } = (context.app.service(path) as AuthenticationManagementService);
 
      const [longToken, shortToken] = await Promise.all([
        getLongToken(options.longTokenLen),
        getShortToken(options.shortTokenLen, options.shortTokenDigits)
      ]);
 
      if (
        (context.method === 'patch' || context.method === 'update') &&
        !!context.params.user &&
        !options.identifyUserProps.some(ensureFieldHasChanged(context.data, context.params.user))
      ) {
        return context;
      }
 
      context.data.isVerified = false;
      // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
      context.data.verifyExpires = Date.now() + options.delay;
      context.data.verifyToken = longToken;
      context.data.verifyShortToken = shortToken;
      context.data.verifyChanges = {};
 
      return context;
    } catch (err) {
      throw new GeneralError(err);
    }
  };
}