all files / lib/strategy/ EnrichIntegrationFromRemoteConfigStrategy.js

84.4% Statements 92/109
68.66% Branches 46/67
89.29% Functions 25/28
84.4% Lines 92/109
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265                                                                                                                                                                                                                        11×       18×         25× 25×     25×                                                                                                                
'use strict';
 
var async = require('async');
var extend = require('../helpers/clone-extend').extend;
var strings = require('../strings');
 
/**
 * Retrieves Stormpath settings from the API service, and ensures the local
 * configuration object properly reflects these settings.
 *
 * @class
*/
function EnrichIntegrationFromRemoteConfigStrategy (clientFactory) {
  this.clientFactory = clientFactory;
}
 
EnrichIntegrationFromRemoteConfigStrategy.prototype._resolveApplication = function (config, callback) {
  var application = config.application;
  if (!application || !application.href || !application.getAccountStoreMappings) {
    callback(new Error(strings.UNABLE_TO_RESOLVE_APP));
  } else {
    callback(null, config.application);
  }
};
 
EnrichIntegrationFromRemoteConfigStrategy.prototype._validateAccountStore = function (config, app, callback) {
  app.getAccountStoreMappings(function (err, mappings) {
    Iif (err) {
      return callback(err);
    }
 
    if (mappings.size === 0) {
      return callback(new Error(strings.NO_ACCOUNT_STORES_MAPPED));
    } else if (config.web.register.enabled && app.defaultAccountStoreMapping === null) {
      return callback(new Error(strings.NO_DEFAULT_ACCOUNT_STORE_MAPPED));
    }
 
    callback(null, app);
  });
};
 
// Returns the OAuth policy of the Stormpath Application.
EnrichIntegrationFromRemoteConfigStrategy.prototype._enrichWithOAuthPolicy = function (app, callback) {
  app.getOAuthPolicy(function(err, policy) {
    Iif (err) {
      return callback(err);
    }
 
    app.oAuthPolicy = policy;
 
    return callback(null, app);
  });
};
 
// Iterate over all account stores on the given Application, looking for all
// Social providers.  We'll then create a config.providers array which we'll
// use later on to dynamically populate all social login configurations ^^
EnrichIntegrationFromRemoteConfigStrategy.prototype._enrichWithSocialProviders = function (config, application, callback) {
  application.getAccountStoreMappings(function(err, mappings) {
    Iif (err) {
      return callback(err);
    }
 
    Eif (!config.web.social) {
      config.web.social = {};
    }
 
    mappings.each(function (mapping, next) {
      mapping.getAccountStore(function (err, accountStore) {
        Iif (err) {
          return next(err);
        }
 
        // Iterate directories
        Eif (/\/directories/.test(accountStore.href)) {
          accountStore.getProvider(function(err, remoteProvider) {
            Iif (err) {
              return next(err);
            }
 
            var providerId = remoteProvider.providerId;
 
            // If the provider isn't a Stormpath, AD, or LDAP directory it's a social directory.
            Eif (['stormpath', 'ad', 'ldap'].indexOf(providerId) === -1) {
              // Remove unnecessary properties that clutter our config.
              delete remoteProvider.href;
              delete remoteProvider.createdAt;
              delete remoteProvider.updatedAt;
 
              var localProvider = config.web.social[providerId];
 
              Eif (!localProvider) {
                localProvider = config.web.social[providerId] = {};
              }
 
              Eif (!localProvider.uri) {
                localProvider.uri = '/callbacks/' + remoteProvider.providerId;
              }
 
              /**
               * "localScope" backwards compatibility code to preserve locally
               * defined scope options.  Soon developers will specify their
               * required scope on the directory provider resource.  But in the
               * meantime, we should not overwrite what they've provided locally.
               */
 
              var localScope;
 
              Iif (localProvider.scope) {
                localScope = localProvider.scope;
              }
 
              extend(remoteProvider, { enabled: true });
              extend(localProvider, remoteProvider);
 
              Iif (localScope) {
                localProvider.scope = localScope;
              }
 
            }
 
            next();
          });
        } else {
          next();
        }
      });
    }, function(err) {
      callback(err, application);
    });
  });
};
 
// Finds and returns an Application's default Account Store (Directory)
// object.  If one doesn't exist, nothing will be returned.
EnrichIntegrationFromRemoteConfigStrategy.prototype._resolveDirectoryHref = function (app, callback) {
  var outerScope = this;
 
  app.getAccountStoreMappings(function(err, mappings) {
    Iif (err) {
      return callback(err);
    }
 
    mappings.detect(function(mapping, detectCallback) {
      detectCallback(mapping.isDefaultAccountStore);
    }, function(defaultMapping) {
      if (defaultMapping) {
        var href = defaultMapping.accountStore.href;
 
        Eif (href.match(/directories/)) {
          return callback(null, href);
        }
 
        if (href.match(/group/)) {
          outerScope.client.getGroup(href, function(err, group) {
            return callback(err, group && group.directory.href);
          });
        } else {
          return callback(null, null);
        }
      } else {
        return callback(null, null);
      }
    });
  });
};
 
// Pulls down all of a Directory's configuration settings,
// and applies them to the local configuration.
EnrichIntegrationFromRemoteConfigStrategy.prototype._enrichWithDirectoryPolicies = function (client, config, directoryHref, callback) {
  if (!directoryHref) {
    return callback(null, null);
  }
 
  // Helper method that checks if a status is set to "enabled".
  var isEnabled = function (status) {
    return status === 'ENABLED';
  };
 
  // Returns the callback immediately if there is an error.
  // Continues processing if there isn't.
  var stopIfError = function (process) {
    return function (err, result) {
      Iif (err) {
        callback(err);
      } else {
        process(result);
      }
    }
  };
 
  // Enrich config with with directory policies.
  client.getDirectory(directoryHref, { expand: 'passwordPolicy,accountCreationPolicy' }, stopIfError(function (directory) {
    var resetEmailStatusEnabled = isEnabled(directory.passwordPolicy.resetEmailStatus);
    var verificationEmailStatusEnabled = isEnabled(directory.accountCreationPolicy.verificationEmailStatus);
 
    // Enrich config with account policies.
    extend(config, {
      web: {
        forgotPassword: {
          enabled: config.web.forgotPassword.enabled === false ? false : resetEmailStatusEnabled
        },
        changePassword: {
          enabled: config.web.changePassword.enabled === false ? false : resetEmailStatusEnabled
        },
        verifyEmail: {
          enabled: config.web.verifyEmail.enabled === false ? false : verificationEmailStatusEnabled
        }
      }
    });
 
    // Validate that auto login and email verification aren't enabled at the same time.
    if (config.web.register.autoLogin && config.web.verifyEmail.enabled) {
      return callback(new Error(strings.CONFLICTING_AUTO_LOGIN_AND_EMAIL_VERIFICATION_CONFIG));
    }
 
    // Enrich config with password policies.
    directory.getPasswordPolicy(stopIfError(function (policy) {
      policy.getStrength(stopIfError(function (strength) {
        // Remove the href property from the Strength Resource, we don't want
        // this to clutter up our nice passwordPolicy configuration
        // dictionary!
        delete strength.href;
 
        config.passwordPolicy = strength;
 
        callback(null, null);
      }));
    }));
  }));
};
 
EnrichIntegrationFromRemoteConfigStrategy.prototype.process = function (config, callback) {
  var tasks = [];
 
  Iif (config.skipRemoteConfig) {
    return callback(null, config);
  }
 
  var client = this.client = this.clientFactory(config);
 
  Eif (config.application && config.application.href) {
    tasks = tasks.concat([
      this._resolveApplication.bind(this, config),
      this._validateAccountStore.bind(this, config),
      this._enrichWithOAuthPolicy.bind(this),
      this._enrichWithSocialProviders.bind(this, config),
      this._resolveDirectoryHref.bind(this),
      this._enrichWithDirectoryPolicies.bind(this, client, config)
    ]);
  }
 
  client.on('error', function (err) {
    callback(err);
  });
 
  client.on('ready', function () {
    async.waterfall(tasks, function (err) {
      callback(err, err ? null : config);
    });
  });
};
 
module.exports = EnrichIntegrationFromRemoteConfigStrategy;