2021-09-01 12:06:51 +02:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const { getOr } = require('lodash/fp');
|
|
|
|
const { policy: policyUtils } = require('@strapi/utils');
|
2021-10-27 18:54:58 +02:00
|
|
|
const { ForbiddenError } = require('@strapi/utils').errors;
|
2021-09-01 12:06:51 +02:00
|
|
|
|
|
|
|
const createPoliciesMiddleware = (resolverConfig, { strapi }) => {
|
|
|
|
return async (resolve, ...rest) => {
|
|
|
|
const resolverPolicies = getOr([], 'policies', resolverConfig);
|
|
|
|
|
|
|
|
// Transform every policy into a unique format
|
|
|
|
const policies = resolverPolicies.map(policy => policyUtils.get(policy));
|
|
|
|
|
|
|
|
// Create a graphql policy context
|
|
|
|
const context = createGraphQLPolicyContext(...rest);
|
|
|
|
|
|
|
|
// Run policies & throw an error if one of them fails
|
|
|
|
for (const policy of policies) {
|
2021-10-04 18:16:28 +02:00
|
|
|
const result = await policy(context, { strapi });
|
2021-09-01 12:06:51 +02:00
|
|
|
|
2021-10-04 18:16:28 +02:00
|
|
|
if (![true, undefined].includes(result)) {
|
2021-10-27 18:54:58 +02:00
|
|
|
throw new ForbiddenError();
|
2021-09-01 12:06:51 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return resolve(...rest);
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
const createGraphQLPolicyContext = (parent, args, context, info) => {
|
|
|
|
return policyUtils.createPolicyContext('graphql', {
|
|
|
|
get parent() {
|
|
|
|
return parent;
|
|
|
|
},
|
|
|
|
|
|
|
|
get args() {
|
|
|
|
return args;
|
|
|
|
},
|
|
|
|
|
|
|
|
get context() {
|
|
|
|
return context;
|
|
|
|
},
|
|
|
|
|
|
|
|
get info() {
|
|
|
|
return info;
|
|
|
|
},
|
|
|
|
|
|
|
|
get state() {
|
|
|
|
return this.context.state;
|
|
|
|
},
|
|
|
|
|
|
|
|
get http() {
|
|
|
|
return this.context.koaContext;
|
|
|
|
},
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
createPoliciesMiddleware,
|
|
|
|
};
|