2022-01-18 16:38:03 +08:00
|
|
|
import { ACLRole, RoleActionParams } from './acl-role';
|
|
|
|
import { ACL, ListenerContext } from './acl';
|
2023-05-24 21:31:12 +08:00
|
|
|
import lodash from 'lodash';
|
2022-01-18 16:38:03 +08:00
|
|
|
|
|
|
|
export type ResourceActions = { [key: string]: RoleActionParams };
|
|
|
|
|
|
|
|
interface AclResourceOptions {
|
|
|
|
name: string;
|
|
|
|
role: ACLRole;
|
|
|
|
actions?: ResourceActions;
|
|
|
|
}
|
|
|
|
|
|
|
|
export class ACLResource {
|
|
|
|
actions = new Map<string, RoleActionParams>();
|
|
|
|
acl: ACL;
|
|
|
|
role: ACLRole;
|
|
|
|
name: string;
|
|
|
|
|
|
|
|
constructor(options: AclResourceOptions) {
|
|
|
|
this.acl = options.role.acl;
|
|
|
|
|
|
|
|
this.role = options.role;
|
|
|
|
this.name = options.name;
|
|
|
|
|
|
|
|
const actionsOption: ResourceActions = options.actions || {};
|
|
|
|
for (const actionName of Object.keys(actionsOption)) {
|
|
|
|
this.actions.set(actionName, actionsOption[actionName]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
getActions() {
|
|
|
|
return Array.from(this.actions.keys()).reduce((carry, key) => {
|
|
|
|
carry[key] = this.actions.get(key);
|
|
|
|
return carry;
|
|
|
|
}, {});
|
|
|
|
}
|
|
|
|
|
|
|
|
getAction(name: string) {
|
2023-05-24 21:31:12 +08:00
|
|
|
const result = this.actions.get(name) || this.actions.get(this.acl.resolveActionAlias(name));
|
|
|
|
if (!result) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Array.isArray(result.fields) && result.fields.length > 0) {
|
|
|
|
result.fields = lodash.uniq(result.fields);
|
|
|
|
}
|
|
|
|
return lodash.cloneDeep(result);
|
2022-01-18 16:38:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
setAction(name: string, params: RoleActionParams) {
|
|
|
|
const context: ListenerContext = {
|
|
|
|
role: this.role,
|
|
|
|
acl: this.role.acl,
|
|
|
|
params: params || {},
|
2022-01-24 14:10:35 +08:00
|
|
|
path: `${this.name}:${name}`,
|
|
|
|
resourceName: this.name,
|
|
|
|
actionName: name,
|
2022-01-18 16:38:03 +08:00
|
|
|
};
|
|
|
|
|
2022-01-24 14:10:35 +08:00
|
|
|
this.acl.emit('beforeGrantAction', context);
|
2022-01-18 16:38:03 +08:00
|
|
|
|
|
|
|
this.actions.set(name, context.params);
|
|
|
|
}
|
|
|
|
|
2022-10-06 10:29:53 +08:00
|
|
|
setActions(actions: ResourceActions) {
|
2022-01-18 16:38:03 +08:00
|
|
|
for (const actionName of Object.keys(actions)) {
|
|
|
|
this.setAction(actionName, actions[actionName]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
removeAction(name: string) {
|
|
|
|
this.actions.delete(name);
|
|
|
|
}
|
|
|
|
}
|