admin-vben/packages/effects/access/src/directive.ts

43 lines
1.0 KiB
TypeScript
Raw Normal View History

2024-07-18 13:31:34 +00:00
/**
* Global authority directive
* Used for fine-grained control of component permissions
* @Example v-access:role="[ROLE_NAME]" or v-access:role="ROLE_NAME"
* @Example v-access:code="[ROLE_CODE]" or v-access:code="ROLE_CODE"
2024-07-18 13:31:34 +00:00
*/
import type { App, Directive, DirectiveBinding } from 'vue';
import { useAccess } from './use-access';
function isAccessible(
el: Element,
binding: DirectiveBinding<string | string[]>,
) {
2024-07-18 13:31:34 +00:00
const { accessMode, hasAccessByCodes, hasAccessByRoles } = useAccess();
const value = binding.value;
if (!value) return;
2024-07-18 13:31:34 +00:00
const authMethod =
accessMode.value === 'frontend' && binding.arg === 'role'
? hasAccessByRoles
: hasAccessByCodes;
2024-07-18 13:31:34 +00:00
const values = Array.isArray(value) ? value : [value];
if (!authMethod(values)) {
2024-07-18 13:31:34 +00:00
el?.remove();
}
}
const mounted = (el: Element, binding: DirectiveBinding<string | string[]>) => {
isAccessible(el, binding);
};
const authDirective: Directive = {
mounted,
};
2024-07-30 13:10:28 +00:00
export function registerAccessDirective(app: App) {
2024-07-18 13:31:34 +00:00
app.directive('access', authDirective);
}