@pothos/plugin-scope-auth
Version:
A Pothos plugin for adding scope based authorization checks to your GraphQL Schema
59 lines (58 loc) • 3.5 kB
JavaScript
import { isThenable } from '@pothos/core';
import { ForbiddenError } from './errors.js';
import RequestCache from './request-cache.js';
import { AuthScopeFailureType } from './types.js';
const defaultUnauthorizedResolver = (_root, _args, _context, _info, error) => {
throw error;
};
export function resolveHelper(steps, plugin, fieldConfig) {
var _plugin_builder_options_scopeAuth;
var _fieldConfig_pothosOptions_unauthorizedResolver;
const unauthorizedResolver = (_fieldConfig_pothosOptions_unauthorizedResolver = fieldConfig.pothosOptions.unauthorizedResolver) !== null && _fieldConfig_pothosOptions_unauthorizedResolver !== void 0 ? _fieldConfig_pothosOptions_unauthorizedResolver : defaultUnauthorizedResolver;
const globalUnauthorizedError = (_plugin_builder_options_scopeAuth = plugin.builder.options.scopeAuth) === null || _plugin_builder_options_scopeAuth === void 0 ? void 0 : _plugin_builder_options_scopeAuth.unauthorizedError;
const defaultUnauthorizedError = (parent, _args, context, info, result) => {
if (globalUnauthorizedError) {
return globalUnauthorizedError(parent, context, info, result);
}
if ((result.failure.kind === AuthScopeFailureType.AuthScope || result.failure.kind === AuthScopeFailureType.AuthScopeFunction) && result.failure.error) {
return result.failure.error;
}
return result.message;
};
var _fieldConfig_pothosOptions_unauthorizedError;
const createError = (_fieldConfig_pothosOptions_unauthorizedError = fieldConfig.pothosOptions.unauthorizedError) !== null && _fieldConfig_pothosOptions_unauthorizedError !== void 0 ? _fieldConfig_pothosOptions_unauthorizedError : defaultUnauthorizedError;
return (parent, args, context, info) => {
let resolvedValue;
const cache = RequestCache.fromContext(context, plugin.builder);
function runSteps(index) {
for (let i = index; i < steps.length; i += 1) {
const { run, errorMessage } = steps[i];
const stepResult = run(cache, parent, args, context, info, (val) => {
resolvedValue = val;
});
if (isThenable(stepResult)) {
return stepResult.then((result) => {
if (result) {
const error = createError(parent, args, context, info, {
message: typeof errorMessage === "function" ? errorMessage(parent, args, context, info) : errorMessage,
failure: result
});
return unauthorizedResolver(parent, args, context, info, typeof error === "string" ? new ForbiddenError(error, result) : error);
}
return runSteps(i + 1);
});
}
if (stepResult) {
const error = createError(parent, args, context, info, {
message: typeof errorMessage === "function" ? errorMessage(parent, args, context, info) : errorMessage,
failure: stepResult
});
return unauthorizedResolver(parent, args, context, info, typeof error === "string" ? new ForbiddenError(error, stepResult) : error);
}
}
return resolvedValue;
}
return runSteps(0);
};
}
//# sourceMappingURL=resolve-helper.js.map