130 lines
2.6 KiB
JavaScript
Raw Normal View History

/**
* Policies util
*/
2022-08-08 15:50:34 +02:00
'use strict';
const _ = require('lodash');
2021-09-24 09:35:25 +02:00
const { eq } = require('lodash/fp');
2021-08-06 18:09:49 +02:00
const PLUGIN_PREFIX = 'plugin::';
2021-08-28 14:16:39 +02:00
const API_PREFIX = 'api::';
const parsePolicy = policy => {
if (typeof policy === 'string') {
return { policyName: policy, config: {} };
}
const { name, config } = policy;
return { policyName: name, config };
};
2021-08-28 14:16:39 +02:00
const searchLocalPolicy = (policyName, { pluginName, apiName }) => {
if (pluginName) {
return strapi.policy(`${PLUGIN_PREFIX}${pluginName}.${policyName}`);
}
2021-08-28 14:16:39 +02:00
if (apiName) {
return strapi.policy(`${API_PREFIX}${apiName}.${policyName}`);
}
};
const globalPolicy = ({ method, endpoint, controller, action, plugin }) => {
return async (ctx, next) => {
ctx.request.route = {
endpoint: `${method} ${endpoint}`,
controller: _.toLower(controller),
action: _.toLower(action),
verb: _.toLower(method),
plugin,
};
await next();
};
};
const resolvePolicies = (config, { pluginName, apiName } = {}) => {
return config.map(policyConfig => {
return {
handler: getPolicy(policyConfig, { pluginName, apiName }),
config: policyConfig.config || {},
};
});
};
const findPolicy = (name, { pluginName, apiName } = {}) => {
const resolvedPolicy = strapi.policy(name);
if (resolvedPolicy !== undefined) {
return resolvedPolicy;
}
const localPolicy = searchLocalPolicy(name, { pluginName, apiName });
if (localPolicy !== undefined) {
return localPolicy;
}
throw new Error(`Could not find policy "${name}"`);
};
const getPolicy = (policyConfig, { pluginName, apiName } = {}) => {
if (typeof policyConfig === 'function') {
return policyConfig;
}
const { policyName, config } = parsePolicy(policyConfig);
const policy = findPolicy(policyName, { pluginName, apiName });
if (typeof policy === 'function') {
return policy;
}
if (policy.validator) {
policy.validator(config);
}
return policy.handler;
};
const createPolicy = options => {
const { name = 'unnamed', validator, handler } = options;
const wrappedValidator = config => {
if (validator) {
try {
validator(config);
} catch (e) {
throw new Error(`Invalid config passed to "${name}" policy.`);
}
}
};
return {
name,
validator: wrappedValidator,
handler,
};
};
2021-09-24 09:35:25 +02:00
const createPolicyContext = (type, ctx) => {
return Object.assign(
{
is: eq(type),
get type() {
return type;
},
},
ctx
);
};
module.exports = {
get: getPolicy,
resolve: resolvePolicies,
globalPolicy,
createPolicy,
2021-09-24 09:35:25 +02:00
createPolicyContext,
};