import { asyncRouter, constantRoutes, user, userLesson, userExam, userSimulation, userScreen, userPlan, superAdmin } from '@/router'; import { PermissionType } from '@/utils/PermissionType'; import { UrlConfig } from '@/router/index'; function setHonePagePath(route, roles) { if (roles && roles.length === 2 && roles.indexOf(user) >= 0 && (route.path === '/' || route.path === 'dashboard')) { if (roles.indexOf(userLesson) >= 0) { route.redirect = `${UrlConfig.teach.home}`; } else if (roles.indexOf(userExam) >= 0) { route.redirect = `${UrlConfig.exam.home}`; } else if (roles.indexOf(userSimulation) >= 0) { route.redirect = `${UrlConfig.demonstration.home}`; } else if (roles.indexOf(userScreen) >= 0) { route.redirect = `${UrlConfig.dp.home}`; } else if (roles.indexOf(userPlan) >= 0) { route.redirect = `${UrlConfig.plan.home}`; } } } /** * 通过meta.role判断是否与当前用户权限匹配 * @param roles * @param route */ function hasPermission(roles, route, parentsRoles) { setHonePagePath(route, roles); if (route.meta && route.meta.roles) { //如果存在本级路由,则使用自己的roles过滤 return roles.some(role => route.meta.roles.indexOf(role) >= 0); } else if (parentsRoles) { //如果没有本级路由,有父级路由,则使用父级路由过滤 return roles.some(role => parentsRoles.indexOf(role) >= 0); } else { //如果父级和本级都没有则默认不需要过滤 return true; } } /** * 根据roles和系统类型重新设置权限列表 * @param roles * @param type */ function convertRouterRoles({ roles, permissionType }) { if (roles && roles.indexOf(user) >= 0) { switch (permissionType) { case PermissionType.LESSON: { roles.push(userLesson); } break; case PermissionType.EXAM: { roles.push(userExam); } break; case PermissionType.SIMULATION: { roles.push(userSimulation); } break; case PermissionType.SCREEN: { roles.push(userScreen); } break; case PermissionType.PLAN: { roles.push(userPlan); } break; } } return { roles }; } /** * 递归过滤异步路由表,返回符合用户角色权限的路由表 * @param asyncRouter * @param roles */ function filterAsyncRouter(asyncRouter, roles, parentsRoles) { return asyncRouter.filter(route => { if (hasPermission(roles, route, parentsRoles)) { if (route.children && route.children.length) { route.children = filterAsyncRouter(route.children, roles, route.meta ? route.meta.roles : undefined); } return true; } return false; }); } const permission = { state: { routes: constantRoutes, addRouters: [], }, mutations: { SET_ROUTERS: (state, routes) => { state.addRouters = routes; state.routes = constantRoutes.concat(routes); } }, actions: { // 生成其他权限路由 GenerateRoutes({ commit }, data) { return new Promise(resolve => { const { roles } = convertRouterRoles(data); let accessedRouters; if (roles.indexOf(superAdmin) >= 0) { accessedRouters = asyncRouter; } else { accessedRouters = filterAsyncRouter(asyncRouter, roles); } commit('SET_ROUTERS', accessedRouters); resolve(); }); } } }; export default permission;