edu/admin/src/permission.ts

85 lines
2.8 KiB
TypeScript
Raw Normal View History

2022-04-08 02:42:44 +00:00
/**
*
*/
import NProgress from 'nprogress'
2022-08-12 10:44:09 +00:00
import router, { findFirstValidRoute } from './router'
2022-04-08 02:42:44 +00:00
import 'nprogress/nprogress.css'
2022-08-12 10:44:09 +00:00
import { isExternal } from './utils/validate'
import useUserStore from './stores/modules/user'
import { INDEX_ROUTE, INDEX_ROUTE_NAME } from './router/routes'
import { PageEnum } from './enums/pageEnum'
import useTabsStore from './stores/modules/multipleTabs'
import { clearAuthInfo } from './utils/auth'
2022-09-20 04:15:36 +00:00
import config from './config'
2022-04-08 02:42:44 +00:00
// NProgress配置
NProgress.configure({ showSpinner: false })
2022-08-12 10:44:09 +00:00
const loginPath = PageEnum.LOGIN
const defaultPath = PageEnum.INDEX
2022-04-08 02:42:44 +00:00
// 免登录白名单
2022-08-12 10:44:09 +00:00
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403]
2022-04-08 02:42:44 +00:00
router.beforeEach(async (to, from, next) => {
// 开始 Progress Bar
2022-08-12 10:44:09 +00:00
NProgress.start()
2022-09-20 04:15:36 +00:00
document.title = to.meta.title ?? config.title
2022-08-12 10:44:09 +00:00
const userStore = useUserStore()
const tabsStore = useTabsStore()
2022-10-13 09:00:50 +00:00
if (whiteList.includes(to.path)) {
// 在免登录白名单,直接进入
next()
} else if (userStore.token) {
2022-04-08 02:42:44 +00:00
// 获取用户信息
2022-08-12 10:44:09 +00:00
const hasGetUserInfo = Object.keys(userStore.userInfo).length !== 0
if (hasGetUserInfo) {
if (to.path === loginPath) {
next({ path: defaultPath })
} else {
next()
}
} else {
2022-04-20 04:10:22 +00:00
try {
2022-08-12 10:44:09 +00:00
await userStore.getUserInfo()
await userStore.getMenu()
const routes = userStore.routes
// 找到第一个有效路由
const routeName = findFirstValidRoute(routes)
// 没有有效路由跳转到403页面
if (!routeName) {
clearAuthInfo()
2022-08-12 10:44:09 +00:00
next(PageEnum.ERROR_403)
return
}
tabsStore.setRouteName(routeName!)
INDEX_ROUTE.redirect = { name: routeName }
// 动态添加index路由
router.addRoute(INDEX_ROUTE)
2022-04-20 04:10:22 +00:00
routes.forEach((route: any) => {
2022-08-12 10:44:09 +00:00
// https 则不插入
if (isExternal(route.path)) {
return
}
if (!route.children) {
router.addRoute(INDEX_ROUTE_NAME, route)
return
}
2022-08-12 10:44:09 +00:00
// 动态添加可访问路由表
router.addRoute(route)
2022-04-20 04:10:22 +00:00
})
2022-08-12 10:44:09 +00:00
next({ ...to, replace: true })
} catch (err) {
clearAuthInfo()
2022-04-20 04:10:22 +00:00
next({ path: loginPath, query: { redirect: to.fullPath } })
}
2022-04-08 02:42:44 +00:00
}
} else {
next({ path: loginPath, query: { redirect: to.fullPath } })
}
})
2022-08-12 10:44:09 +00:00
router.afterEach(() => {
2022-04-08 02:42:44 +00:00
NProgress.done()
})