import NProgress from 'nprogress'; import 'nprogress/nprogress.css'; import { createRouter, createWebHistory, createWebHashHistory, } from 'vue-router'; import { constantRoutes } from './routers'; import { getAccessToken } from '@/plugins/auth-token'; import { validHttp } from '@/utils/regular-utils'; import useUserStore from '@/store/modules/user'; import useAppStore from '@/store/modules/app'; import useNeListStore from '@/store/modules/ne_list'; import useRouterStore from '@/store/modules/router'; // NProgress Configuration NProgress.configure({ showSpinner: false }); // 根据.env配置获取是否带井号和基础路径 const hasHash = import.meta.env.VITE_HISTORY_HASH; const bashUrl = import.meta.env.VITE_HISTORY_BASE_URL; /**全局路由 */ const router = createRouter({ history: hasHash === 'true' ? createWebHashHistory(bashUrl) : createWebHistory(bashUrl), routes: constantRoutes, scrollBehavior(to, from, savedPosition) { if (savedPosition) { return savedPosition; } else { return { top: 0 }; } }, }); /**全局路由-后置守卫 */ router.afterEach((to, from, failure) => { NProgress.done(); const title = to.meta?.title; // 设置标题 if (!failure && title) { useAppStore().setTitle(to.meta.title); } }); /**无Token可访问页面地址白名单 */ const WHITE_LIST: string[] = [ '/login', '/auth-redirect', '/help', '/register', '/quick-start', '/trace-task-hlr', ]; /**全局路由-前置守卫 */ router.beforeEach(async (to, from, next) => { NProgress.start(); // 获取系统配置信息 const appStore = useAppStore(); if (!appStore.loginBackground) { await appStore.fnSysConf(); } // // 需要系统引导跳转 // if (appStore.bootloader && to.path !== '/quick-start') { // next({ name: 'QuickStart' }); // } // // 不重复引导 // if (!appStore.bootloader && to.path === '/quick-start') { // next({ name: 'Index' }); // } let token = getAccessToken(); // 免用户登录认证 if (!appStore.loginAuth) { token = '== Not Login Auth =='; } // 没有token if (!token) { if (WHITE_LIST.includes(to.path)) { // 在免登录白名单,直接进入 next(); } else { // 否则全部重定向到登录页 next(`/login?redirect=${to.fullPath}`); } } // 有Token if (token) { if (to.path === '/login') { // 防止重复访问登录页面 next({ name: 'Index' }); } else { // 判断当前用户是否有角色信息 const user = useUserStore(); if (user.roles && user.roles.length === 0) { try { // 获取网元信息 await useNeListStore().fnNelist(); // 获取用户信息 await user.fnGetInfo(); // 获取路由信息 const accessRoutes = await useRouterStore().generateRoutes(); // 根据后台配置生成可访问的路由表 if (accessRoutes && accessRoutes.length !== 0) { for (const route of accessRoutes) { // 动态添加可访问路由表,http开头会异常 if (!validHttp(route.path)) { router.addRoute(route); } } } // 刷新替换原先路由,确保addRoutes已完成 next({ ...to, replace: true }); } catch (error: any) { console.error(`[${to.path}]: ${error.message}`); await user.fnLogOut(); next({ name: 'Login' }); } } else if ( to.meta.neType && to.meta.neType.length > 0 && !useNeListStore().fnHasNe(to.meta.neType) ) { next({ name: 'NotPermission' }); } else { next(); } } } }); export default router;