all files / express-stormpath/lib/helpers/ validate-account.js

100% Statements 21/21
100% Branches 21/21
100% Functions 5/5
100% Lines 21/21
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 71                                        31× 31×   31× 31× 120×     120×   31× 31×   31×       31×                               31× 31× 131×       31×        
'use strict';
 
var async = require('async');
 
var getRequiredRegistrationFields = require('./get-required-registration-fields');
 
/**
 * @private
 * @callback validateAccountCallback
 * @param {Error[]} errors - An array of Account validation errors (if there
 *  are any).  Will be null if no errors are present and the Account is valid.
 */
 
/**
 * Validate that all required Account data is present and valid before
 * attempting to create an Account on Stormpath.  If any required fields are
 * missing or invalid, an array of errors will be returned.
 *
 * @param {Object} formData - The user supplied form data for registration.
 * @param {Object} stormpathConfig - The Stormpath configuration object.
 * @param {validateAccountCallback} callback - The callback to run.
 */
module.exports = function (formData, stormpathConfig, callback) {
  var accountFieldNames = Object.keys(formData);
  var errors = [];
 
  getRequiredRegistrationFields(stormpathConfig, function (requiredFields) {
    async.each(requiredFields, function (field, cb) {
      if (accountFieldNames.indexOf(field.name) <= -1 || (accountFieldNames.indexOf(field.name) > -1 && !formData[field.name])) {
        errors.push(new Error((field.label || field.label) + ' required.'));
      }
 
      cb();
    }, function () {
      var registerFields = stormpathConfig.web.register.form.fields;
      var confirmPasswordField = registerFields.confirmPassword;
 
      if (confirmPasswordField && confirmPasswordField.enabled) {
        if (formData.password !== formData.confirmPassword) {
          errors.push(new Error('Passwords do not match.'));
        }
      }
 
      var coreFields = [
        'username',
        'email',
        'password',
        'givenName',
        'middleName',
        'surname',
        'status',
        'password',
        'customData'
      ];
 
      /*
        Find all the fields that are not core account fields.  If they are not defined
        in the registration configuration, they should be rejected.
       */
      var configuredFieldNames = Object.keys(registerFields);
      accountFieldNames.concat(Object.keys(formData.customData || {})).forEach(function (fieldName) {
        if (coreFields.indexOf(fieldName) === -1 && configuredFieldNames.indexOf(fieldName) === -1) {
          errors.push(new Error(fieldName + ' is not a configured registration field.'));
        }
      });
 
      return errors.length ? callback(errors) : callback(null);
    });
  });
};