2023-10-25 10:26:14 +08:00
|
|
|
import type { RouteLocationNormalized, RouteRecordNormalized, RouteRecordRaw } from 'vue-router';
|
2023-09-25 22:05:48 +08:00
|
|
|
import { useMenuStore, useUserStore } from '@/store';
|
2024-03-22 16:32:37 +08:00
|
|
|
import { DEFAULT_ROUTER, STATUS_ROUTER_LIST, WHITE_ROUTER_LIST } from '@/router/constants';
|
2023-11-24 02:07:52 +08:00
|
|
|
import { AdminRoleCode } from '@/types/const';
|
2023-07-24 10:05:07 +08:00
|
|
|
|
|
|
|
|
export default function usePermission() {
|
2023-09-25 22:05:48 +08:00
|
|
|
const menuStore = useMenuStore();
|
2023-07-24 10:05:07 +08:00
|
|
|
const userStore = useUserStore();
|
|
|
|
|
return {
|
2023-08-02 17:08:40 +08:00
|
|
|
/**
|
|
|
|
|
* 是否可访问路由
|
|
|
|
|
*/
|
2023-07-24 10:05:07 +08:00
|
|
|
accessRouter(route: RouteLocationNormalized | RouteRecordRaw) {
|
2023-08-15 18:34:09 +08:00
|
|
|
// 没有名字证明路由不存在
|
|
|
|
|
if (route.name === undefined) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
2023-08-02 17:54:12 +08:00
|
|
|
// 检查路由是否存在于授权路由中
|
2024-03-22 16:32:37 +08:00
|
|
|
const menuConfig = [...menuStore.appMenus, ...WHITE_ROUTER_LIST, ...STATUS_ROUTER_LIST, DEFAULT_ROUTER];
|
2023-08-02 17:54:12 +08:00
|
|
|
let exist = false;
|
|
|
|
|
while (menuConfig.length && !exist) {
|
|
|
|
|
const element = menuConfig.shift();
|
|
|
|
|
if (element?.name === route.name) exist = true;
|
|
|
|
|
if (element?.children) {
|
|
|
|
|
menuConfig.push(
|
|
|
|
|
...(element.children as unknown as RouteRecordNormalized[])
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return exist;
|
2023-07-24 10:05:07 +08:00
|
|
|
},
|
2023-08-02 17:08:40 +08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 是否有权限
|
|
|
|
|
*/
|
|
|
|
|
hasPermission(permission: string) {
|
|
|
|
|
return userStore.permission?.includes('*') ||
|
|
|
|
|
userStore.permission?.includes(permission);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 是否有权限
|
|
|
|
|
*/
|
|
|
|
|
hasAnyPermission(permission: string[]) {
|
|
|
|
|
return userStore.permission?.includes('*') ||
|
|
|
|
|
permission.map(s => userStore.permission?.includes(s))
|
2024-03-22 16:32:37 +08:00
|
|
|
.filter(Boolean).length > 0;
|
2023-07-24 10:05:07 +08:00
|
|
|
},
|
2023-08-02 17:08:40 +08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 是否有角色
|
|
|
|
|
*/
|
|
|
|
|
hasRole(role: string) {
|
2023-11-24 02:07:52 +08:00
|
|
|
return userStore.roles?.includes(AdminRoleCode) ||
|
2023-08-02 17:08:40 +08:00
|
|
|
userStore.roles?.includes(role);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 是否有角色
|
|
|
|
|
*/
|
|
|
|
|
hasAnyRole(role: string[]) {
|
2023-11-24 02:07:52 +08:00
|
|
|
return userStore.roles?.includes(AdminRoleCode) ||
|
2023-08-02 17:08:40 +08:00
|
|
|
role.map(s => userStore.roles?.includes(s))
|
2024-03-22 16:32:37 +08:00
|
|
|
.filter(Boolean).length > 0;
|
2023-08-02 17:08:40 +08:00
|
|
|
}
|
2023-07-24 10:05:07 +08:00
|
|
|
};
|
|
|
|
|
}
|