2022-01-18 16:38:03 +08:00
|
|
|
import lodash from 'lodash';
|
2022-01-18 20:29:41 +08:00
|
|
|
import { ACL } from './acl';
|
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?: '*';
|
|
|
|
}
|
|
|
|
|
|
|
|
export function strategyValueMatched(strategy: StrategyValue, value: string) {
|
|
|
|
if (strategy === '*') {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (lodash.isString(strategy) && strategy === value) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (lodash.isArray(strategy) && strategy.includes(value)) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this.actionsAsObject?.hasOwnProperty(actionName)) {
|
|
|
|
const predicateName = this.actionsAsObject[actionName];
|
|
|
|
if (predicateName) {
|
|
|
|
return predicate[predicateName];
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
if (this.acl.isConfigResource(resourceName) && this.allowConfigure) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return this.matchAction(this.acl.resolveActionAlias(actionName));
|
2022-01-18 16:38:03 +08:00
|
|
|
}
|
|
|
|
}
|