WEB/src/permission.ts
2026-05-04 00:34:56 +08:00

84 lines
2.8 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'
NProgress.configure({ showSpinner: false })
const whiteList = ['/login','/redirect','/admin/land'] // no redirect whitelist
router.beforeEach(async (to, from) => {
NProgress.start()
// console.log("路由表",router.getRoutes());
document.title = getPageTitle(to.meta.title as string)
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()
})