@elsikora/nestjs-crud-automator
Version:
A library for automating the creation of CRUD operations in NestJS.
67 lines (64 loc) • 2.66 kB
JavaScript
import { ApiSubscriberBase } from '../../subscriber/base.class.js';
import { EAuthorizationEffect } from '../../../../enum/class/authorization/effect.enum.js';
/**
* Base class for all authorization policies. It mirrors ApiFunctionSubscriberBase
* and provides helper methods to create allow/deny rules that are later executed by the policy executor.
* @template E - Entity type extending IApiBaseEntity
*/
class ApiAuthorizationPolicyBase extends ApiSubscriberBase {
/**
* Creates an ALLOW rule with optional overrides.
* @param {Omit<IApiAuthorizationPolicySubscriberRule<E>, "effect">} [rule] - Rule fields to merge.
* @returns {IApiAuthorizationPolicySubscriberRule<E>} Allow rule.
*/
allow(rule = {}) {
return {
effect: EAuthorizationEffect.ALLOW,
...rule,
};
}
/**
* Helper that creates an allow rule conditioned on the subject having at least one of the provided roles.
* @param {Array<string>} roles - Roles that grant access.
* @param {Omit<IApiAuthorizationPolicySubscriberRule<E>, "effect">} [rule] - Optional overrides.
* @returns {IApiAuthorizationPolicySubscriberRule<E>} Allow rule targeting the given roles.
*/
allowForRoles(roles, rule = {}) {
return this.allow({
condition: ({ subject }) => roles.some((role) => subject.roles.includes(role)),
...rule,
});
}
/**
* Creates a DENY rule with optional overrides.
* @param {Omit<IApiAuthorizationPolicySubscriberRule<E>, "effect">} [rule] - Rule fields to merge.
* @returns {IApiAuthorizationPolicySubscriberRule<E>} Deny rule.
*/
deny(rule = {}) {
return {
effect: EAuthorizationEffect.DENY,
...rule,
};
}
/**
* Helper that scopes data access to the owner identified by a field.
* Automatically handles relations by using nested id structure.
* @param {keyof E} [ownerField] - Entity field used to match the subject id, defaults to ownerId.
* @param {Omit<IApiAuthorizationPolicySubscriberRule<E>, "effect">} [rule] - Optional overrides.
* @returns {IApiAuthorizationPolicySubscriberRule<E>} Allow rule with owner scope.
*/
scopeToOwner(ownerField = "ownerId", rule = {}) {
return this.allow({
scope: ({ subject }) => {
return {
where: {
[ownerField]: { id: subject.id },
},
};
},
...rule,
});
}
}
export { ApiAuthorizationPolicyBase };
//# sourceMappingURL=base.class.js.map