import { Recordable } from '@eciol/types'; import type { Router, RouteRecordRaw } from 'vue-router'; import { PAGE_NOT_FOUND_NAME } from '../constant'; import { context } from '../context'; export function createPermissionGuard(router: Router) { const userStore = context.useUserStoreWithOut(); const permissionStore = context.usePermissionStoreWithOut(); const whitePathList: any[] = [context.PageEnum.BASE_LOGIN]; router.beforeEach(async (to, from, next) => { if ( from.path === context.RootRoute.path && to.path === context.PageEnum.BASE_HOME && userStore.getUserInfo.homePath && userStore.getUserInfo.homePath !== context.PageEnum.BASE_HOME ) { next(userStore.getUserInfo.homePath); return; } const token = userStore.getToken; // Whitelist can be directly entered if (whitePathList.includes(to.path as any)) { if (to.path === (context.PageEnum.BASE_LOGIN as string) && token) { const isSessionTimeout = userStore.getSessionTimeout; try { await userStore.afterLoginAction(); if (!isSessionTimeout) { next((to.query?.redirect as string) || '/'); return; } } catch { // } } next(); return; } // token or user does not exist if (!token) { // You can access without permission. You need to set the routing meta.ignoreAuth to true if (to.meta.ignoreAuth) { next(); return; } if (context.isOutLogin) { window.location.href = context.PageEnum.BASE_LOGIN as string; return; } // redirect login page const redirectData: { path: string; replace: boolean; query?: Recordable } = { path: context.PageEnum.BASE_LOGIN, replace: true, }; if (to.path) { redirectData.query = { ...redirectData.query, redirect: to.path, }; } next(redirectData); return; } // Jump to the 404 page after processing the login if ( from.path === (context.PageEnum.BASE_LOGIN as string) && to.name === PAGE_NOT_FOUND_NAME && to.fullPath !== (userStore.getUserInfo.homePath || context.PageEnum.BASE_HOME) ) { next(userStore.getUserInfo.homePath || context.PageEnum.BASE_HOME); return; } // get userinfo while last fetch time is empty if (userStore.getLastUpdateTime === 0) { try { await userStore.getUserInfoAction(); } catch (err) { next(); return; } } if (permissionStore.getIsDynamicAddedRoute) { next(); return; } const routes = await permissionStore.buildRoutesAction(); routes.forEach((route: any) => { router.addRoute(route as unknown as RouteRecordRaw); }); router.addRoute(context.PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw); permissionStore.setDynamicAddedRoute(true); if (to.name === PAGE_NOT_FOUND_NAME) { // 动态添加路由后,此处应当重定向到fullPath,否则会加载404页面内容 next({ path: to.fullPath, replace: true, query: to.query }); } else { const redirectPath = (from.query.redirect || to.path) as string; const redirect = decodeURIComponent(redirectPath); const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }; next(nextData); } }); }