2023-02-02 16:07:38 +08:00
|
|
|
import router from '@/router'
|
|
|
|
import { filterAsyncRouter, progressClose, progressStart } from '@/hooks/use-permission'
|
|
|
|
import { useBasicStore } from '@/store/basic'
|
2023-02-23 14:24:56 +08:00
|
|
|
import { getMyInfo, getMyRole } from '@/api/user'
|
2023-02-02 16:07:38 +08:00
|
|
|
import { langTitle } from '@/hooks/use-common'
|
2023-02-23 14:24:56 +08:00
|
|
|
import { getRouterList } from '@/api/router'
|
2023-02-02 16:07:38 +08:00
|
|
|
|
|
|
|
//路由进入前拦截
|
|
|
|
//to:将要进入的页面 vue-router4.0 不推荐使用next()
|
2023-06-06 08:46:30 +08:00
|
|
|
const whiteList = ['/login', '/404', '/401', '/500'] // no redirect whitelist
|
2023-02-02 16:07:38 +08:00
|
|
|
router.beforeEach(async (to) => {
|
|
|
|
progressStart()
|
|
|
|
document.title = langTitle(to.meta?.title) // i18 page title
|
|
|
|
const basicStore = useBasicStore()
|
2023-06-06 08:46:30 +08:00
|
|
|
if (to.path === '/500') {
|
|
|
|
return true
|
|
|
|
}
|
2023-02-02 16:07:38 +08:00
|
|
|
//1.判断token
|
|
|
|
if (basicStore.token) {
|
|
|
|
if (to.path === '/login') {
|
|
|
|
return '/'
|
|
|
|
} else {
|
|
|
|
//2.判断是否获取用户信息
|
|
|
|
if (!basicStore.getUserInfo) {
|
|
|
|
try {
|
2023-02-23 14:24:56 +08:00
|
|
|
const [userData, userRole] = await Promise.all([getMyInfo(), getMyRole()])
|
|
|
|
const routes = await getRouterList({ roleId: userRole.roleId })
|
2023-02-02 16:07:38 +08:00
|
|
|
//3.动态路由权限筛选
|
2023-02-23 14:24:56 +08:00
|
|
|
filterAsyncRouter({ menuList: routes })
|
2023-02-02 16:07:38 +08:00
|
|
|
//4.保存用户信息到store
|
2023-02-23 14:24:56 +08:00
|
|
|
basicStore.setUserInfo({
|
|
|
|
userInfo: userData,
|
|
|
|
roles: [userRole.roleType],
|
|
|
|
codes: [userRole.roleId]
|
|
|
|
})
|
2023-02-02 16:07:38 +08:00
|
|
|
//5.再次执行路由跳转
|
|
|
|
return { ...to, replace: true }
|
|
|
|
} catch (e) {
|
|
|
|
console.error(`route permission error${e}`)
|
|
|
|
basicStore.resetState()
|
|
|
|
progressClose()
|
2023-06-06 08:46:30 +08:00
|
|
|
return `/500?redirect=${to.path}`
|
2023-02-02 16:07:38 +08:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if (!whiteList.includes(to.path)) {
|
|
|
|
return `/login?redirect=${to.path}`
|
|
|
|
} else {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
//路由进入后拦截
|
|
|
|
router.afterEach(() => {
|
|
|
|
progressClose()
|
|
|
|
})
|