All files / src/hooks add-verification.js

94.44% Statements 17/18
100% Branches 8/8
83.33% Functions 5/6
94.44% Lines 17/18

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  1x 1x 1x   1x     18x 13x   13x 13x 13x                   13x         1x     12x 12x 12x 12x 12x   12x              
 
const errors = require('@feathersjs/errors');
const { checkContext } = require('feathers-hooks-common');
const { getLongToken, getShortToken, ensureFieldHasChanged } = require('../helpers');
 
module.exports = addVerification;
 
function addVerification (path) {
  return hook => {
    checkContext(hook, 'before', ['create', 'patch', 'update']);
 
    return Promise.resolve()
      .then(() => hook.app.service(path || 'authManagement').create({ action: 'options' }))
      .then(options => Promise.all([
        options,
        getLongToken(options.longTokenLen),
        getShortToken(options.shortTokenLen, options.shortTokenDigits)
      ]))
      .then(([options, longToken, shortToken]) => {
        // We do NOT add verification fields if the 3 following conditions are fulfilled:
        // - hook is PATCH or PUT
        // - user is authenticated
        // - user's identifyUserProps fields did not change
        if (
          (hook.method === 'patch' || hook.method === 'update') &&
          !!hook.params.user &&
          !options.identifyUserProps.some(ensureFieldHasChanged(hook.data, hook.params.user))
        ) {
          return hook;
        }
 
        hook.data.isVerified = false;
        hook.data.verifyExpires = Date.now() + options.delay;
        hook.data.verifyToken = longToken;
        hook.data.verifyShortToken = shortToken;
        hook.data.verifyChanges = {};
 
        return hook;
      })
      .catch(err => {
        throw new errors.GeneralError(err);
      });
  };
}