@elsikora/nestjs-crud-automator
Version:
A library for automating the creation of CRUD operations in NestJS.
93 lines (90 loc) • 3.19 kB
JavaScript
;
var tslib_es6 = require('../../../external/tslib/tslib.es6.js');
var effect_enum = require('../../../enum/class/authorization/effect.enum.js');
var common = require('@nestjs/common');
var where_utility = require('../../../utility/authorization/scope/merge/where.utility.js');
exports.ApiAuthorizationEngine = class ApiAuthorizationEngine {
async evaluate(options) {
const context = {
resource: options.resource,
subject: options.subject,
};
const matchedRules = [];
let scope;
const transforms = [];
for (const rule of options.policy.rules) {
const isConditionPassed = await this.evaluateCondition(rule, context);
if (!isConditionPassed) {
continue;
}
if (rule.effect === effect_enum.EAuthorizationEffect.DENY) {
return this.buildDecision(options, {
appliedRules: [rule],
effect: effect_enum.EAuthorizationEffect.DENY,
scope: undefined,
transforms: [],
});
}
matchedRules.push(rule);
scope = await this.mergeScope(scope, rule, context);
if (rule.resultTransform) {
transforms.push(rule.resultTransform);
}
}
if (matchedRules.length === 0) {
return this.buildDecision(options, {
appliedRules: [],
effect: effect_enum.EAuthorizationEffect.DENY,
scope: undefined,
transforms: [],
});
}
return this.buildDecision(options, {
appliedRules: matchedRules,
effect: effect_enum.EAuthorizationEffect.ALLOW,
scope,
transforms,
});
}
buildDecision(options, payload) {
return {
action: options.action,
appliedRules: payload.appliedRules,
effect: payload.effect,
policyId: options.policy.policyId,
resource: options.resource,
resourceType: options.policy.entity.name ?? "UnknownResource",
scope: payload.scope,
subject: options.subject,
transforms: payload.transforms,
};
}
async evaluateCondition(rule, context) {
if (!rule.condition) {
return true;
}
const result = await rule.condition(context);
return result === true;
}
async mergeScope(currentScope, rule, context) {
if (!rule.scope) {
return currentScope;
}
const scopePatch = await rule.scope(context);
if (!scopePatch) {
return currentScope;
}
if (!currentScope) {
return scopePatch;
}
return {
...currentScope,
...scopePatch,
where: where_utility.AuthorizationScopeMergeWhere(currentScope.where, scopePatch.where),
};
}
};
exports.ApiAuthorizationEngine = tslib_es6.__decorate([
common.Injectable()
], exports.ApiAuthorizationEngine);
//# sourceMappingURL=engine.class.js.map