/* * @Author: 李佐宁 lizuoning@yuan-info.com * @Date: 2022-07-12 19:15:28 * @LastEditors: changjun * @LastEditTime: 2022-09-15 16:59:52 * @FilePath: /yuan-qingdao-zld-browser/src/router/guard/index.ts */ import type { Router, RouteRecordRaw } from "vue-router"; import { usePermissionStoreWithOut } from "../../store/modules/permission"; import { getTokenValueCache } from "../../utils/auth/token"; type Recordable = Record; import {handleMenuToRoute} from '../../utils/tools' import { useUserStoreWithOut } from '../../store/modules/users' import { PAGE_NOT_FOUND_ROUTE } from '../../router/routes/basic'; import { appSetting } from '../../settings/index' export function createPermissionGuard(router: Router) { const permissionStore = usePermissionStoreWithOut(); const userStore = useUserStoreWithOut(); let routes = [] as any // 白名单,无需登录即可跳转 const whitePathList = ['/login', '/404', '/502']; router.beforeEach(async (to, from, next) => { if (whitePathList.includes(to.path)) { next(); return; } const token = getTokenValueCache(); console.log('路由获取token', token) // token不存在 if (!token) { // redirect login page const redirectData: { name: string; replace: boolean; query?: Recordable; } = { name: "Login", replace: true, }; if (to.path) { redirectData.query = { ...redirectData.query, redirect: to.path, }; } next(redirectData); return; } // 如果是导入证书页面,不获取菜单直接进入 if(to.name === 'ImportLicense'){ next(); return; } // 如果用户是第一次登录不再获取剩余菜单权限直接跳转到强制修改密码页面 if(userStore.getHasFirstLogin()){ if(to.name === 'ChangeInitPassword'){ console.log(to.name) console.log('第一次登录') next() return }else{ userStore.logoutAction(router) return; } } if (permissionStore.getIsDynamicAddedRoute) { const noMatchAccessRoute = routes.length > 0 ? routes[0] : '' // 如果是去首页,或者从首页重定向过来时候,需要判断一下当前用户角色是否拥有首页菜单权限,如果无的话跳转到用户角色权限第一个菜单 if((to.path === '/' || from.path === '/') && to.name === "PageNotFound" && noMatchAccessRoute) { next({ path: noMatchAccessRoute.path, replace: true }) return; } if(to.path === '/'){ next({ path: appSetting.HomePath, replace: true, }); return; } next(); return; } routes = await permissionStore.buildRoutesAction() || []; console.log('获取到的动态路由', routes) routes.forEach((route) => { router.addRoute(route as unknown as RouteRecordRaw); }); router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw); permissionStore.setDynamicAddedRoute(true); if (to.name === PAGE_NOT_FOUND_ROUTE.name) { // 动态添加路由后,此处应当重定向到fullPath,否则会加载404页面内容 next({ path: to.fullPath, replace: true, query: to.query }); } else { const redirectPath = (from.query.redirect || to.path) as string; console.log('重定向路径', redirectPath) const redirect = decodeURIComponent(redirectPath); const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }; next(nextData); } }); }