This commit is contained in:
Your Name
2026-08-27 14:04:28 +08:00
parent f7720831be
commit 334890171e
3016 changed files with 263403 additions and 27971 deletions
@@ -0,0 +1,29 @@
{
"name": "@vben/access",
"version": "5.7.0",
"homepage": "https://github.com/vbenjs/vue-vben-admin",
"bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
"repository": {
"type": "git",
"url": "git+https://github.com/vbenjs/vue-vben-admin.git",
"directory": "packages/effects/permissions"
},
"license": "MIT",
"type": "module",
"sideEffects": [
"**/*.css"
],
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
}
},
"dependencies": {
"@vben/preferences": "workspace:*",
"@vben/stores": "workspace:*",
"@vben/types": "workspace:*",
"@vben/utils": "workspace:*",
"vue": "catalog:"
}
}
@@ -0,0 +1,240 @@
import type { RouteRecordRaw } from '@vben/types';
import { describe, expect, it } from 'vitest';
import { generateAccessible } from '../accessible';
// generateAccessible 会操作传入的 router 实例。这里用最小 stub 覆盖它实际调用的方法:
// - getRoutes(): 返回 [] -> 不存在根路由 '/', 走 router.addRoute 分支
// - addRoute/removeRoute: 空实现
// 我们只断言返回的 accessibleRoutes 上自动生成的 redirect。
function createRouterStub() {
return {
addRoute: () => {},
getRoutes: () => [],
removeRoute: () => {},
} as any;
}
async function generate(routes: RouteRecordRaw[]) {
const { accessibleRoutes } = await generateAccessible('frontend', {
router: createRouterStub(),
routes,
});
return accessibleRoutes;
}
function findByName(
routes: RouteRecordRaw[],
name: string,
): RouteRecordRaw | undefined {
for (const route of routes) {
if (route.name === name) {
return route;
}
if (route.children) {
const found = findByName(route.children as RouteRecordRaw[], name);
if (found) {
return found;
}
}
}
return undefined;
}
describe('generateAccessible - redirect normalization', () => {
it('不为动态参数(:id)首子路由的父级生成 redirect', async () => {
const routes = [
{
name: 'DyeSets',
path: 'dye-sets',
children: [
{
name: 'DyeSetDetail',
path: ':id',
meta: { hideInMenu: true, title: 'detail' },
},
],
meta: { title: 'dye-sets' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
expect(findByName(result, 'DyeSets')?.redirect).toBeUndefined();
});
it('父级为对象 redirect({name}) 且含 :id 子路由时不抛异常且不生成 redirect', async () => {
const routes = [
{
name: 'Production',
path: '/production',
redirect: { name: 'ProductionTasks' },
children: [
{
name: 'ProductionTasks',
path: 'production-tasks',
children: [
{
name: 'ProductionTaskDetail',
path: ':id',
meta: { hideInMenu: true, title: 'detail' },
},
{
name: 'ProductionTaskMatch',
path: ':id/match',
meta: { hideInMenu: true, title: 'match' },
},
],
meta: { title: 'tasks' },
},
],
meta: { title: 'production' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
// 顶级对象 redirect 保持不变
expect(findByName(result, 'Production')?.redirect).toEqual({
name: 'ProductionTasks',
});
// :id 首子路由的父级不生成 redirect
expect(findByName(result, 'ProductionTasks')?.redirect).toBeUndefined();
});
it('父级为对象 redirect 时,普通相对首子路由回退用 parent.path 拼接', async () => {
const routes = [
{
name: 'Setting',
path: '/setting',
redirect: { name: 'SettingService' },
children: [
{
name: 'SettingGroup',
path: 'group',
children: [
{
name: 'SettingService',
path: 'service',
meta: { title: 'service' },
},
],
meta: { title: 'group' },
},
],
meta: { title: 'setting' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
expect(findByName(result, 'SettingGroup')?.redirect).toBe(
'/setting/group/service',
);
});
it('深层嵌套(上游风格)相对路径逐级生成正确的累计绝对 redirect', async () => {
const routes = [
{
name: 'Demos',
path: '/demos',
children: [
{
name: 'NestedDemos',
path: 'nested',
children: [
{
name: 'Menu1Demo',
path: 'menu1',
meta: { title: 'menu1' },
},
{
name: 'Menu2Demo',
path: 'menu2',
children: [
{
name: 'Menu21Demo',
path: 'menu2-1',
meta: { title: 'menu2-1' },
},
],
meta: { title: 'menu2' },
},
],
meta: { title: 'nested' },
},
],
meta: { title: 'demos' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
// Demos 重定向到第一级子路由,子路由继续级联到叶子
expect(findByName(result, 'Demos')?.redirect).toBe('/demos/nested');
expect(findByName(result, 'NestedDemos')?.redirect).toBe(
'/demos/nested/menu1',
);
expect(findByName(result, 'Menu2Demo')?.redirect).toBe(
'/demos/nested/menu2/menu2-1',
);
});
it('首子路由为绝对路径(/foo)时不生成 redirect', async () => {
const routes = [
{
name: 'Dashboard',
path: '/dashboard',
children: [
{
name: 'Analytics',
path: '/analytics',
meta: { title: 'analytics' },
},
],
meta: { title: 'dashboard' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
expect(findByName(result, 'Dashboard')?.redirect).toBeUndefined();
});
it('首子路由为空 path 时不生成 redirect', async () => {
const routes = [
{
name: 'HideChildrenParent',
path: 'hide-menu-children',
children: [
{
name: 'HideChildren',
path: '',
meta: { title: 'hide' },
},
],
meta: { title: 'parent' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
expect(findByName(result, 'HideChildrenParent')?.redirect).toBeUndefined();
});
it('已存在的 redirect 保持不变', async () => {
const routes = [
{
name: 'Custom',
path: '/custom',
redirect: '/custom/keep',
children: [
{
name: 'CustomChild',
path: 'child',
meta: { title: 'child' },
},
],
meta: { title: 'custom' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
expect(findByName(result, 'Custom')?.redirect).toBe('/custom/keep');
});
});
@@ -0,0 +1,47 @@
<!--
Access control component for fine-grained access control.
TODO: 可以扩展更完善的功能
1. 支持多个权限码只要有一个权限码满足即可 或者 多个权限码全部满足
2. 支持多个角色只要有一个角色满足即可 或者 多个角色全部满足
3. 支持自定义权限码和角色的判断逻辑
-->
<script lang="ts" setup>
import { computed } from 'vue';
import { useAccess } from './use-access';
interface Props {
/**
* Specified codes is visible
* @default []
*/
codes?: string[];
/**
* 通过什么方式来控制组件,如果是 role,则传入角色,如果是 code,则传入权限码
* @default 'role'
*/
type?: 'code' | 'role';
}
defineOptions({
name: 'AccessControl',
});
const props = withDefaults(defineProps<Props>(), {
codes: () => [],
type: 'role',
});
const { hasAccessByCodes, hasAccessByRoles } = useAccess();
const hasAuth = computed(() => {
const { codes, type } = props;
return type === 'role' ? hasAccessByRoles(codes) : hasAccessByCodes(codes);
});
</script>
<template>
<slot v-if="!codes"></slot>
<slot v-else-if="hasAuth"></slot>
</template>
@@ -0,0 +1,240 @@
import type { Component, DefineComponent } from 'vue';
import type {
AccessModeType,
GenerateMenuAndRoutesOptions,
RouteRecordRaw,
} from '@vben/types';
import { defineComponent, h } from 'vue';
import {
cloneDeep,
generateMenus,
generateRoutesByBackend,
generateRoutesByFrontend,
isFunction,
isString,
mapTree,
} from '@vben/utils';
async function generateAccessible(
mode: AccessModeType,
options: GenerateMenuAndRoutesOptions,
) {
const { router } = options;
options.routes = cloneDeep(options.routes);
// 生成路由
const accessibleRoutes = await generateRoutes(mode, options);
const root = router.getRoutes().find((item) => item.path === '/');
// 获取已有的路由名称列表
const names = root?.children?.map((item) => item.name) ?? [];
// 动态添加到router实例内
accessibleRoutes.forEach((route) => {
if (root && !route.meta?.noBasicLayout) {
// 为了兼容之前的版本用法,如果包含子路由,则将component移除,以免出现多层BasicLayout
// 如果你的项目已经跟进了本次修改,移除了所有自定义菜单首级的BasicLayout,可以将这段if代码删除
if (route.children && route.children.length > 0) {
delete route.component;
}
// 根据router name判断,如果路由已经存在,则不再添加
if (names?.includes(route.name)) {
// 找到已存在的路由索引并更新,不更新会造成切换用户时,一级目录未更新,homePath 在二级目录导致的404问题
const index = root.children?.findIndex(
(item) => item.name === route.name,
);
if (index !== undefined && index !== -1 && root.children) {
root.children[index] = route;
}
} else {
root.children?.push(route);
}
} else {
router.addRoute(route);
}
});
if (root) {
if (root.name) {
router.removeRoute(root.name);
}
router.addRoute(root);
}
// 生成菜单
const accessibleMenus = generateMenus(accessibleRoutes, options.router);
return { accessibleMenus, accessibleRoutes };
}
/**
* Generate routes
* @param mode
* @param options
*/
async function generateRoutes(
mode: AccessModeType,
options: GenerateMenuAndRoutesOptions,
) {
const { forbiddenComponent, roles, routes } = options;
let resultRoutes: RouteRecordRaw[] = routes;
switch (mode) {
case 'backend': {
resultRoutes = await generateRoutesByBackend(options);
break;
}
case 'frontend': {
resultRoutes = await generateRoutesByFrontend(
routes,
roles || [],
forbiddenComponent,
);
break;
}
case 'mixed': {
const [frontend_resultRoutes, backend_resultRoutes] = await Promise.all([
generateRoutesByFrontend(routes, roles || [], forbiddenComponent),
generateRoutesByBackend(options),
]);
resultRoutes = mergeRoutesByName(
backend_resultRoutes,
frontend_resultRoutes,
);
break;
}
}
/**
* 调整路由树,做以下处理:
* 1. 对未添加redirect的路由添加redirect
* 2. 将懒加载的组件名称修改为当前路由的名称(如果启用了keep-alive的话)
*/
resultRoutes = mapTree(resultRoutes, (route, parent) => {
// 重新包装component,使用与路由名称相同的name以支持keep-alive的条件缓存。
if (
route.meta?.keepAlive &&
isFunction(route.component) &&
route.name &&
isString(route.name)
) {
const originalComponent = route.component as () => Promise<{
default: Component | DefineComponent;
}>;
route.component = async () => {
const component = await originalComponent();
if (!component.default) return component;
return defineComponent({
name: route.name as string,
setup(props, { attrs, slots }) {
return () => h(component.default, { ...props, ...attrs }, slots);
},
});
};
}
// 如果有redirect或者没有子路由,则直接返回
if (route.redirect || !route.children || route.children.length === 0) {
return route;
}
const firstChild = route.children[0];
if (!firstChild?.path || firstChild.path.startsWith('/')) {
return route;
}
// fork 定制:如果第一个子路由是动态路由(如 :id),说明当前路由本身是一个
// “列表+详情”页面(渲染自身组件),不应自动重定向到未填充的动态参数,
// 否则地址栏会出现字面量 ":id" 或匹配失败导致 404。
// 详见对上游重构 commit f00a8812 的修复。
if (firstChild.path.startsWith(':')) {
return route;
}
// 拼接子路由的重定向绝对路径。
// - 当 parent.redirect 为字符串时,它已经是累计好的绝对路径,直接替换最后一段
// 即可正确支持任意层级的深层嵌套(如 /demos/nested/menu2/menu2-1)。
// - fork 定制:后端菜单可能传入对象形式的 redirect(如 { name }),无法 split
// 此时回退到使用 parent.path 拼接(这类 parent 为顶级路由,path 为绝对路径)。
if (parent && parent.redirect && isString(parent.redirect)) {
const parentSplit = parent.redirect.split('/');
parentSplit.splice(-1, 2, route.path, firstChild.path);
const redirectPath = parentSplit.join('/');
route.redirect = redirectPath;
} else if (parent && parent.redirect) {
route.redirect = `${parent.path}/${route.path}/${firstChild.path}`;
} else {
route.redirect = `${route.path}/${firstChild.path}`;
}
return route;
});
return resultRoutes;
}
/**
* 根据 name 合并前后端路由
* @param baseRoutes 后端路由
* @param extraRoutes 前端路由
*/
function mergeRoutesByName(
baseRoutes: RouteRecordRaw[],
extraRoutes: RouteRecordRaw[],
): RouteRecordRaw[] {
const result: RouteRecordRaw[] = [];
const routeMap = new Map<string, RouteRecordRaw>();
for (const route of baseRoutes) {
const clone = { ...route } as RouteRecordRaw;
result.push(clone);
if (clone.name && isString(clone.name)) {
routeMap.set(clone.name as string, clone);
}
}
for (const route of extraRoutes) {
if (
route.name &&
isString(route.name) &&
routeMap.has(route.name as string)
) {
const existing = routeMap.get(route.name as string);
if (!existing) {
continue;
}
const existingChildren = existing.children ?? [];
const routeChildren = route.children ?? [];
const merged = {
...route,
...existing, // keep backend as base
meta: {
...route.meta,
...existing.meta, // backend meta wins on conflicts
},
} as RouteRecordRaw;
if (existingChildren.length > 0 || routeChildren.length > 0) {
merged.children = mergeRoutesByName(existingChildren, routeChildren);
}
Object.assign(existing, merged);
} else {
const clone = { ...route } as RouteRecordRaw;
result.push(clone);
if (clone.name && isString(clone.name)) {
routeMap.set(clone.name as string, clone);
}
}
}
return result;
}
export { generateAccessible };
@@ -0,0 +1,42 @@
/**
* 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"
*/
import type { App, Directive, DirectiveBinding } from 'vue';
import { useAccess } from './use-access';
function isAccessible(
el: Element,
binding: DirectiveBinding<string | string[]>,
) {
const { accessMode, hasAccessByCodes, hasAccessByRoles } = useAccess();
const value = binding.value;
if (!value) return;
const authMethod =
accessMode.value === 'frontend' && binding.arg === 'role'
? hasAccessByRoles
: hasAccessByCodes;
const values = Array.isArray(value) ? value : [value];
if (!authMethod(values)) {
el?.remove();
}
}
const mounted = (el: Element, binding: DirectiveBinding<string | string[]>) => {
isAccessible(el, binding);
};
const authDirective: Directive = {
mounted,
};
export function registerAccessDirective(app: App) {
app.directive('access', authDirective);
}
@@ -0,0 +1,4 @@
export { default as AccessControl } from './access-control.vue';
export * from './accessible';
export * from './directive';
export * from './use-access';
@@ -0,0 +1,53 @@
import { computed } from 'vue';
import { preferences, updatePreferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';
function useAccess() {
const accessStore = useAccessStore();
const userStore = useUserStore();
const accessMode = computed(() => {
return preferences.app.accessMode;
});
/**
* 基于角色判断是否有权限
* @description: Determine whether there is permissionThe role is judged by the user's role
* @param roles
*/
function hasAccessByRoles(roles: string[]) {
const userRoleSet = new Set(userStore.userRoles);
const intersection = roles.filter((item) => userRoleSet.has(item));
return intersection.length > 0;
}
/**
* 基于权限码判断是否有权限
* @description: Determine whether there is permissionThe permission code is judged by the user's permission code
* @param codes
*/
function hasAccessByCodes(codes: string[]) {
const userCodesSet = new Set(accessStore.accessCodes);
const intersection = codes.filter((item) => userCodesSet.has(item));
return intersection.length > 0;
}
async function toggleAccessMode() {
updatePreferences({
app: {
accessMode:
preferences.app.accessMode === 'frontend' ? 'backend' : 'frontend',
},
});
}
return {
accessMode,
hasAccessByCodes,
hasAccessByRoles,
toggleAccessMode,
};
}
export { useAccess };
@@ -0,0 +1,6 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@vben/tsconfig/web.json",
"include": ["src"],
"exclude": ["node_modules"]
}