UNPKG

1.76 kBJavaScriptView Raw
1const fs = require('fs');
2const chalk = require('chalk');
3const path = require('path');
4const logger = require('../logger').policy;
5const schemas = require('../schemas');
6
7const register = (policyOptions) => {
8 const { name, schema, policy: action } = policyOptions;
9
10 const validate = schemas.register('policy', name, schema);
11
12 policyOptions.policy = (params, ...args) => {
13 const validationResult = validate(params);
14 if (validationResult.isValid) {
15 return action(params, ...args);
16 }
17
18 logger.error(`Policy ${chalk.default.red.bold(name)} params validation failed: ${validationResult.error}`);
19 throw new Error(`POLICY_PARAMS_VALIDATION_FAILED`);
20 };
21
22 policies[name] = policyOptions;
23};
24
25const resolve = (policyName) => {
26 const policy = policies[policyName];
27
28 if (!policy) {
29 logger.error(`Could not find policy ${policyName}, Please make sure the plugins providing such policy
30 is correctly configured in system.config file.`);
31 throw new Error('POLICY_NOT_FOUND');
32 }
33
34 return policy;
35};
36
37const policies = {};
38
39schemas.register('internal', 'baseAuth', {
40 $id: 'http://express-gateway.io/schemas/base/auth.json',
41 type: 'object',
42 properties: {
43 passThrough: {
44 type: 'boolean',
45 default: false,
46 description: 'Specify whether continue with pipeline processing in case the authentication fails'
47 }
48 },
49 required: ['passThrough']
50});
51
52const policyNames = fs
53 .readdirSync(path.resolve(__dirname))
54 .filter(dir => fs.lstatSync(path.resolve(__dirname, dir)).isDirectory());
55
56policyNames.forEach((name) => {
57 const policy = require(path.resolve(__dirname, name));
58 policies[name] = Object.assign(policy, { name });
59 register(policy);
60});
61
62module.exports = { register, resolve, policies };