WEB/src/permission.ts
2026-10-18 17:57:06 +08:00

128 lines
4.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import router from './router'
import { useUserStore } from '@/stores/modules/user'
import { useUserPreferenceStore } from '@/stores/modules/userPreference'
import { usePermissionStore } from '@/stores/modules/permission'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { usePrinterComponentStore } from '@/stores/modules/printerComponent'
import type { RouteRecordRaw } from 'vue-router'
type RouteLogNode = {
path: string
name?: string | symbol
redirect?: RouteRecordRaw['redirect']
meta?: RouteRecordRaw['meta']
children?: RouteLogNode[]
}
/** 格式化路由树,便于控制台查看(去掉 component 等不可序列化字段) */
function formatRoutesForLog(routes: readonly RouteRecordRaw[]): RouteLogNode[] {
return routes.map((route) => ({
path: route.path,
name: route.name,
redirect: route.redirect,
meta: route.meta,
children: route.children?.length ? formatRoutesForLog(route.children) : undefined
}))
}
NProgress.configure({ showSpinner: false })
const whiteList = ['/login','/redirect','/admin/land','/test'] // no redirect whitelist
/** 登录后“一次连接”:先加载用户偏好(含打印组件分用户+仓库配置),再自动连接一次 */
function ensurePrinterConnectionsAfterLogin() {
if (!getToken()) return
const prefs = useUserPreferenceStore()
if (!prefs.isLoaded) prefs.load()
usePrinterComponentStore().startConnections()
}
/** 页签“刷新”经 /redirect 软刷新(非整页重载),标记为回到目标页后执行一次打印组件重连 */
let pendingRefreshReconnect = false
/** 软刷新回到目标路由后:执行一次打印组件重连(登录守卫路径外的补充触发点) */
function maybeRetryPrintConnectionsAfterRefresh() {
if (!pendingRefreshReconnect) return
pendingRefreshReconnect = false
if (!getToken()) return
usePrinterComponentStore().retryConnectionsOnce()
}
router.beforeEach(async (to, from) => {
NProgress.start()
// console.log("路由表",router.getRoutes());
// 页面/浏览器标题统一由 App.vue(组件读 frontBrand store)设置,此处不再设置
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') {
NProgress.done()
return { path: '/' }
} else {
// 页签“刷新”:先经 /redirect 中转(软刷新),回到目标页后执行一次打印组件重连
if (to.path.startsWith('/redirect')) {
pendingRefreshReconnect = true
}
const userStore = useUserStore()
const hasGetUserInfo = userStore.user && userStore.user.employees_name
if (hasGetUserInfo) {
ensurePrinterConnectionsAfterLogin()
maybeRetryPrintConnectionsAfterRefresh()
return true
} else {
try {
// get user info
const user = await userStore.getInfo()
// 加载用户偏好配置(浏览器本地保存:登录 + 整页刷新均在此触发),再触发登录后自动连接(按用户+仓库配置执行一次)
useUserPreferenceStore().load()
ensurePrinterConnectionsAfterLogin()
maybeRetryPrintConnectionsAfterRefresh()
const permissionStore = usePermissionStore()
// generate accessible routes based on menus
const accessRoutes = await permissionStore.generateRoutes(user.menus || [])
// dynamically add accessible routes
accessRoutes.forEach(route => {
router.addRoute(route)
})
console.log('[Router] 动态路由 (后端菜单转换):', formatRoutesForLog(accessRoutes))
console.log('[Router] 合并后完整路由 (constantRoutes + 动态):', formatRoutesForLog(permissionStore.routes))
console.log('[Router] Vue Router 实例路由:', formatRoutesForLog(router.getRoutes()))
// hack method to ensure that addRoutes is complete
// set the replace: true, so the navigation will not leave a history record
return { ...to, replace: true }
} catch (error) {
// remove token and go to login page to re-login
await userStore.resetToken()
ElMessage.error((error as any).message || 'Has Error')
NProgress.done()
return `/login?redirect=${to.path}`
}
}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
// in the free login whitelist, go directly
return true
} else {
// other pages that do not have permission to access are redirected to the login page.
NProgress.done()
return `/login?redirect=${to.path}`
}
}
})
router.afterEach(() => {
NProgress.done()
})