all files / express-stormpath/lib/helpers/ prep-account-data.js

83.33% Statements 20/24
62.5% Branches 10/16
100% Functions 3/3
83.33% Lines 20/24
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                                        16×       16×       16×       16×                     16×   16× 70× 70× 64×                 16×    
'use strict';
 
/**
 * @private
 * @callback prepAccountDataCallback
 * @param {Object} accountData - The prepared Stormpath Account data that is now
 *  ready to be created.
 */
 
/**
 * Takes in form data from a registration request, and converts it into a
 * valid Stormpath account object.
 *
 * This consists of extracting all non-core fields into customData to ensure
 * arbitrary data gets copied over to custom data upon account creation.
 *
 * @param {Object} formData - The user supplied form data.
 * @param {Object} stormpathConfig - The Stormpath configuration object.
 * @param {prepAccountDataCallback} callback - The callback to run.
 */
module.exports = function (formData, stormpathConfig, callback) {
  Iif (!formData) {
    throw new Error('prepAccountData must be provided with a formData argument.');
  }
 
  Iif (!stormpathConfig) {
    throw new Error('prepAccountData must be provided with a stormpathConfig argument.');
  }
 
  Iif (!callback) {
    throw new Error('prepAccountData must be provided with a callback argument.');
  }
 
  var coreFields = [
    'username',
    'email',
    'password',
    'givenName',
    'middleName',
    'surname',
    'status',
    'password'
  ];
 
  var accountObject = { };
 
  Object.keys(formData).forEach(function (key) {
    var value = formData[key];
    if (coreFields.indexOf(key) > -1) {
      accountObject[key] = value;
    } else if (key === 'customData') {
      Eif (accountObject.customData) {
        Object.keys(value).reduce(function (customData, field) {
          customData[field] = value[field];
          return customData;
        }, accountObject.customData);
      } else {
        accountObject.customData = value;
      }
    } else Eif (key !== 'confirmPassword') {
      Eif (!accountObject.customData) {
        accountObject.customData = {};
      }
      accountObject.customData[key] = value;
    }
  });
 
  callback(accountObject);
};