2022-01-18 16:38:03 +08:00
|
|
|
import lodash from 'lodash';
|
2022-01-18 20:29:41 +08:00
|
|
|
import { ACL } from './acl';
|
2024-03-03 23:06:24 +08:00
|
|
|
|
2022-01-18 16:38:03 +08:00
|
|
|
type StrategyValue = false | '*' | string | string[];
|
|
|
|
|
|
|
|
export interface AvailableStrategyOptions {
|
|
|
|
displayName?: string;
|
2022-01-24 14:10:35 +08:00
|
|
|
actions?: false | string | string[];
|
|
|
|
allowConfigure?: boolean;
|
2022-01-18 16:38:03 +08:00
|
|
|
resource?: '*';
|
|
|
|
}
|
|
|
|
|
2022-01-24 14:10:35 +08:00
|
|
|
export const predicate = {
|
|
|
|
own: {
|
|
|
|
filter: {
|
|
|
|
createdById: '{{ ctx.state.currentUser.id }}',
|
|
|
|
},
|
|
|
|
},
|
|
|
|
all: {},
|
|
|
|
};
|
|
|
|
|
2022-01-18 16:38:03 +08:00
|
|
|
export class ACLAvailableStrategy {
|
2022-01-24 14:10:35 +08:00
|
|
|
acl: ACL;
|
2022-01-18 16:38:03 +08:00
|
|
|
options: AvailableStrategyOptions;
|
2022-01-24 14:10:35 +08:00
|
|
|
actionsAsObject: { [key: string]: string };
|
2022-01-18 16:38:03 +08:00
|
|
|
|
2022-01-24 14:10:35 +08:00
|
|
|
allowConfigure: boolean;
|
|
|
|
|
|
|
|
constructor(acl: ACL, options: AvailableStrategyOptions) {
|
|
|
|
this.acl = acl;
|
2022-01-18 16:38:03 +08:00
|
|
|
this.options = options;
|
2022-01-24 14:10:35 +08:00
|
|
|
this.allowConfigure = options.allowConfigure;
|
|
|
|
|
|
|
|
let actions = this.options.actions;
|
|
|
|
if (lodash.isString(actions) && actions != '*') {
|
|
|
|
actions = [actions];
|
|
|
|
}
|
|
|
|
|
|
|
|
if (lodash.isArray(actions)) {
|
|
|
|
this.actionsAsObject = actions.reduce((carry, action) => {
|
|
|
|
const [actionName, predicate] = action.split(':');
|
|
|
|
carry[actionName] = predicate;
|
|
|
|
return carry;
|
|
|
|
}, {});
|
|
|
|
}
|
2022-01-18 16:38:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
matchAction(actionName: string) {
|
2022-01-24 14:10:35 +08:00
|
|
|
if (this.options.actions == '*') {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2024-03-03 23:06:24 +08:00
|
|
|
if (Object.prototype.hasOwnProperty.call(this.actionsAsObject || {}, actionName)) {
|
2022-01-24 14:10:35 +08:00
|
|
|
const predicateName = this.actionsAsObject[actionName];
|
|
|
|
if (predicateName) {
|
2023-01-09 07:35:48 +08:00
|
|
|
return lodash.cloneDeep(predicate[predicateName]);
|
2022-01-24 14:10:35 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
2022-01-18 16:38:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
allow(resourceName: string, actionName: string) {
|
2022-01-24 14:10:35 +08:00
|
|
|
return this.matchAction(this.acl.resolveActionAlias(actionName));
|
2022-01-18 16:38:03 +08:00
|
|
|
}
|
|
|
|
}
|