WEB/src/permission.ts
2026-05-06 17:44:37 +08:00

102 lines
3.6 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 { usePermissionStore } from '@/stores/modules/permission'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'
import i18n from '@/lang'
NProgress.configure({ showSpinner: false })
/** 与侧边栏 / 标签一致:优先按路由 name、再按 meta.title 匹配 menu.* 文案 */
function resolveRouteDocumentTitle(route: typeof router.currentRoute.value) {
const tryMenuKey = (raw: unknown) => {
if (raw === undefined || raw === null || raw === '') return ''
const key = String(raw).replace(/_Child$/, '')
const path = `menu.${key}`
return i18n.global.te(path) ? String(i18n.global.t(path)) : ''
}
const metaTitle = route.meta?.title as string | undefined
const fromName = tryMenuKey(route.name)
if (fromName) return fromName
const fromMetaAsKey = tryMenuKey(metaTitle)
if (fromMetaAsKey) return fromMetaAsKey
return metaTitle || (route.name != null ? String(route.name) : '')
}
const whiteList = ['/login','/redirect','/admin/land'] // no redirect whitelist
router.beforeEach(async (to, from) => {
NProgress.start()
// console.log("路由表",router.getRoutes());
document.title = getPageTitle(resolveRouteDocumentTitle(to))
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') {
NProgress.done()
return { path: '/' }
} else {
const userStore = useUserStore()
const hasGetUserInfo = userStore.user && userStore.user.employees_name
if (hasGetUserInfo) {
return true
} else {
try {
// get user info
const user = await userStore.getInfo()
const permissionStore = usePermissionStore()
// generate accessible routes based on menus
const accessRoutes = await permissionStore.generateRoutes(user.menus || [])
// console.log('从后端获取并转换后的动态路由:', accessRoutes)
// console.log('合并后的前端完整路由表 (添加前):', router.getRoutes())
// dynamically add accessible routes
accessRoutes.forEach(route => {
router.addRoute(route)
})
// 打印已添加的动态路由信息与添加后的完整路由表,便于调试
try {
// console.log('已添加的动态路由 paths:', accessRoutes.map(r => r.path))
} catch (e) {
// console.log('已添加的动态路由 (无法列出 paths):', accessRoutes)
}
// console.log('合并后的前端完整路由表 (添加后):', 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()
})