Load all policy configurations
@return {Promise<[Policy]>} - promise of an array of policies
778201
function loadPolicies() {
  const policyConfigsPath = path.join(process.cwd(), plugin.config.policiesPath);

  // This event allows to inject code before loading all APIs
  return plugin.myrmex.fire('beforePoliciesLoad')
  .then(() => {
    // Retrieve configuration path of all API specifications
    return fs.readdirAsync(policyConfigsPath);
  })
  .then(policyConfigFiles => {
    // Load all the policy configurations
    const policyPromises = [];
    _.forEach(policyConfigFiles, (filename) => {
      const policyConfigPath = path.join(policyConfigsPath, filename);
      const policyName = path.parse(filename).name;
      policyPromises.push(loadPolicy(policyConfigPath, policyName));
    });
    return Promise.all(policyPromises);
  })
  .then(policies => {
    // This event allows to inject code to add or delete or alter policy configurations
    return plugin.myrmex.fire('afterPoliciesLoad', policies);
  })
  .spread(policies => {
    return Promise.resolve(policies);
  })
  .catch(e => {
    if (e.code === 'ENOENT' && path.basename(e.path) === 'policies') {
      return Promise.resolve([]);
    }
    return Promise.reject(e);
  });
}
721856
function loadSecurityContext () {
	AuthModel = models[inflector.pluralize(configuration.security.model)];
	const Model = models[inflector.pluralize(configuration.security.model)];
	/* istanbul ignore if */
	if (!Model) {
		return;
	}
	passport.serializeUser(function (user, done) {
		done(null, user._id);
	});
	passport.deserializeUser(function (id, done) {
		Model.findById(id).then(done.bind(null, null), done);
	});
	for (const strategy of Object.keys(configuration.security.strategies)) {
		const STR = configuration.security.strategies[strategy];
		try {
			let component = STR.package || /* istanbul ignore next: I have to change the proyect structure */`passport-${strategy}`;
			let Strategy = require(ProyPath('node_modules', component));
			let args = [];
			/* istanbul ignore next */
			if (STR.strategy) {
				Strategy = Strategy[STR.strategy];
			}
			/* istanbul ignore else */
			if (STR.identifier) {
				args.push(STR.identifier);
			}
			/* istanbul ignore else */
			if (STR.options) {
				args.push(new Strategy(STR.options, STR.secret || getuser));
			} else {
				args.push(new Strategy(STR.secret || getuser));
			}
			passport.use(...args);
		} catch (err) /* istanbul ignore next */ {
			debug(err);
			debug(inflector.camelize(`${strategy}_strategy`) + ' not found');
			debug(`You might try npm install ${STR.package}`);
		}
	}
}
631387
function listPolicyInstances ({ id, organizationId, type }, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      Joi.validate({ id, organizationId, type }, validationRules.listPolicyInstances, function (err) {
        if (err) return cb(Boom.badRequest(err))

        const sqlQuery = SQL`          
          SELECT entity_type, entity_id, policy_instance, variables, policy_id FROM
          (SELECT 'user' as entity_type, user_id as entity_id, variables, policy_instance, policy_id
          FROM user_policies
          WHERE policy_id = ${id}
          UNION
          SELECT 'team' as entity_type, team_id as entity_id, variables, policy_instance, policy_id
          FROM team_policies
          WHERE policy_id = ${id}
          UNION
          SELECT 'organization' as entity_type, org_id as entity_id, variables, policy_instance, policy_id
          FROM organization_policies
          WHERE policy_id = ${id}) as policy_instances
          INNER JOIN policies 
          ON policies.id = policy_instances.policy_id
        `

        if (type === 'shared') {
          sqlQuery.append(SQL` WHERE org_id is NULL`)
        } else {
          sqlQuery.append(SQL` WHERE org_id=${organizationId}`)
        }
        sqlQuery.append(SQL` ORDER BY entity_type, policy_instance`)

        db.query(sqlQuery, function (err, result) {
          if (err) return cb(Boom.badImplementation(err))
          if (result.rowCount === 0) return cb(null, [])
          return cb(null, result.rows.map(mapping.policy.instances))
        })
      })
      return promise
    }
609694
function promiseReadFiles(pattern) {
  return glob(pattern)
    .then(foundFiles => {
      const promisesToReadFiles = foundFiles.map(fileName => pReadFile(fileName));

      return Promise.all(promisesToReadFiles);
    })
    .catch(log.error);
}
512887
function loadConfiguration() {
    let configuration;

    if (isInit()) {
        configuration = jsonReader('./.versionFilesList.json');

        // check configuration file's integrity
        if (!configuration.name || !configuration.currentVersion || !configuration.filesList || !configuration.versionPrefix) {
            sendError('E002');
        }

        // check .versionFilesList.json for missing informations
        if (configuration.name.length === 0 || configuration.currentVersion.length === 0) {
            sendError('E001');
        }
    }
    return configuration;
}
77989
function getChoices() {
    return {
      policyIdentifiers: () => {
        return plugin.loadPolicies()
        .then(policies => {
          // Build the list of available policies for input verification and interactive selection
          return _.map(policies, policy => {
            return {
              value: policy.name,
              name: policy.name + (policy.description ? ' - ' + policy.description : '')
            };
          });
        });
      }
    };
  }
235747
def versions(options = {})
      batches = Enumerator.new do |y|
        options = options.merge(policy_arn: @arn)
        resp = @client.list_policy_versions(options)
        resp.each_page do |page|
          batch = []
          page.data.versions.each do |v|
            batch << PolicyVersion.new(
              arn: @arn,
              version_id: v.version_id,
              data: v,
              client: @client
            )
          end
          y.yield(batch)
        end
      end
      PolicyVersion::Collection.new(batches)
    end
1293640
function read(callback) {
        let raw = fs.readFileSync(thing.path).toString()
        //let json = thing.path.split('.').reverse()[0] === 'json'
        // TODO add support for role.yaml
        let policies = JSON.parse(raw).policies
        callback(null, policies || [])
      }
331536
function readPolicyVariables ({ id, organizationId, type }, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      Joi.validate({ id, organizationId, type }, validationRules.readPolicyVariables, function (err) {
        if (err) return cb(Boom.badRequest(err))

        const sqlQuery = SQL`
          SELECT  *
          FROM policies
          WHERE id = ${id}
        `

        if (type === 'shared') {
          sqlQuery.append(SQL` AND org_id is NULL`)
        } else {
          sqlQuery.append(SQL` AND org_id=${organizationId}`)
        }

        db.query(sqlQuery, function (err, result) {
          if (err) return cb(Boom.badImplementation(err))
          if (result.rowCount === 0) return cb(Boom.notFound())

          let variables = []

          _.each(result.rows[0].statements.Statement, function (statement) {
            if (statement.Resource) {
              _.map(statement.Resource, function (resource) {
                // ignore context vars but list all others, should match validation.js
                let variableMatches = resource.match(/\${((?!(udaru)|(request)).*)(.+?)}/g)
                _.each(variableMatches, function (variable) {
                  variables.push(variable)
                })
              })
            }
          })

          return cb(null, variables)
        })
      })

      return promise
    }
1192848
function loadResources (styleArray) {
  const publicPath = '/public';
  var results = {};
  for (let source of styleArray) {
    if (source.resources) {
      for (let category in source.resources) {
        if (source.resources.hasOwnProperty(category)) {
          if (!results.hasOwnProperty(category)) {
            results[category] = {};
          }
          for (let item in source.resources[category]) {
            results[category][item] = source.resources[category][item];
            results[category][item].dataPromise = new Promise(resolve => {
              getJSON(publicPath + results[category][item].src)
                .then(data => {
                  resolve(data);
                });
            });
          }
        }
      }
    }
  }
  return results;
}
90299
function loadSimpleResourceMap(config) {
    return new Promise((resolve, reject) => {

        // Convert Jest config into glob pattern.
        let testPathDirs;
        let testFileExtensions;
        let generatedGlob;

        if (config.testPathDirs.length === 1) {
            testPathDirs = config.testPathDirs[0];
        } else {
            testPathDirs = '{' + config.testPathDirs.join(',') + '}';
        }

        if (config.testFileExtensions.length === 1) {
            testFileExtensions = config.testFileExtensions[0];
        } else {
            testFileExtensions = '{' + config.testFileExtensions.join(',') + '}';
        }

        generatedGlob = testPathDirs + '/' +
            '**/' + config.testDirectoryName + '/**/*.' + testFileExtensions;

        glob(generatedGlob, (err, files) => {
            if (err) {
                reject(err);
            } else {
                let resourceMap;
                resourceMap = {
                    resourcePathMap: {}
                };
                files.forEach(file => {
                    let fullPath = path.resolve(file);
                    resourceMap.resourcePathMap[fullPath] = {
                        path: fullPath
                    };
                });
                resolve(resourceMap);
            }
        });
    });
}
112661
function() {
        var self = this;

        return new Promise(function(resolve, reject) {
            var config = {};

            for (var i = 0; i < self._modules.length; i++) {
                var module = self._modules[i];

                var storedModule = config[module.name] = {
                    dependencies: module.dependencies
                };

                if (module.condition) {
                    storedModule.condition = module.condition;
                }

                if (!self._options.ignorePath) {
                    if (module.fullPath) {
                        storedModule.fullPath = upath.toUnix(module.fullPath);
                    } else {
                        var dirname = path.dirname(module.name);

                        var modulePath = module.path || (dirname !== '.' ? dirname + '/' + module.file : module.file);

                        storedModule.path = upath.toUnix(modulePath);
                    }
                }
            }

            resolve(config);
        });
    }
230075
function any (definitions, failureCode = 'policy_failed', failureMessage = 'The request did not satisfy any required policy.') {
  function isTrue (value) {
    return value === true;
  }

  return Policy.extend ({
    failureCode,

    failureMessage,

    /// Collection of policies to check.
    policies: null,

    init () {
      this._super.call (this, ...arguments);
      this.policies = compact (definitions.map (policy => policyMaker (policy, this.app)));
    },

    runCheck (req) {
      return Promise.all (this.policies.map (policy => policy.runCheck (req)))
        .then (results => some (results, isTrue));
    }
  });
}
391959
function load(template) {
  return new Promise((resolve, reject) => {
    const promise = Benchpress.loader(template, (templateFunction) => {
      resolve(templateFunction);
    });

    if (promise && promise.then) {
      promise.then(resolve, reject);
    }
  });
}
982852
function() {
			var configuration = this.config;
			if (!configuration) {
				var pid = this.pid, self = this;
				this.configPromise = this.configPromise ||
					Deferred.all([
						this.configAdmin.getDefaultConfiguration(pid),
						this.configAdmin.getConfiguration(pid)
					]).then(function(result) {
						self.defaultConfig = result[0];
						self.config = result[1];
						return self.config;
					});
				return this.configPromise;
			}
			return new Deferred().resolve(configuration);
		}
545970
function findPolicies(identifiers) {
  return loadPolicies()
  .then((policies) => {
    return _.filter(policies, (policy) => { return identifiers.indexOf(policy.name) !== -1; });
  });
}
1338729
public static function loadAll()
  {
    static $list = [];
    if (!empty($list)) {
      return $list;
    }
    foreach (self::getPolicyList() as $definition) {
      try {
        $list[$definition['name']] = self::loadPolicyByName($definition['name']);
      }
      catch (\Exception $e) {
        Container::getLogger()->warning("[{$definition['name']}] " . $e->getMessage());
      }
    }
    return $list;
  }