tachybase_todo/packages/acl/src/acl-available-strategy.ts
ChengLei Shao bd285e0ba9
Plugin acl (#166)
* feat: getRepository

* getRepository return type

* export action

* add: acl

* feat: setResourceAction

* feat: action alias

* chore: code struct

* feat: removeResourceAction

* chore: file name

* ignorecase

* remove ACL

* feat: ACL

* feat: role toJSON

* using emit

* chore: test

* feat: plugin-acl

* feat: acl with predicate

* grant universal action test

* grant action test

* update resource action test

* revoke resource action

* usingActionsConfig switch

* plugin-ui-schema-storage

* remove global acl instance

* fix: collection manager with sqlite

* add own action listener

* add acl middleware

* add acl allowConfigure strategy option

* add plugin-acl allowConfigure

* change acl resourceName

* add acl middleware merge params

* bugfix

* append fields on acl action params

* acl middleware parse template

* fix: collection-manager migrate

Co-authored-by: chenos <chenlinxh@gmail.com>
2022-01-24 14:10:35 +08:00

88 lines
1.9 KiB
TypeScript

import lodash from 'lodash';
import { ACL } from './acl';
type StrategyValue = false | '*' | string | string[];
export interface AvailableStrategyOptions {
displayName?: string;
actions?: false | string | string[];
allowConfigure?: boolean;
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;
}
export const predicate = {
own: {
filter: {
createdById: '{{ ctx.state.currentUser.id }}',
},
},
all: {},
};
export class ACLAvailableStrategy {
acl: ACL;
options: AvailableStrategyOptions;
actionsAsObject: { [key: string]: string };
allowConfigure: boolean;
constructor(acl: ACL, options: AvailableStrategyOptions) {
this.acl = acl;
this.options = options;
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;
}, {});
}
}
matchAction(actionName: string) {
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;
}
allow(resourceName: string, actionName: string) {
if (this.acl.isConfigResource(resourceName) && this.allowConfigure) {
return true;
}
return this.matchAction(this.acl.resolveActionAlias(actionName));
}
}