123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- import router, { asyncRoutes } from '@/router'
- import settings from './settings'
- import { getToken, setToken, TokenKey } from '@/utils/auth'
- import NProgress from 'nprogress'
- NProgress.configure({ showSpinner: false }) // NProgress Configuration
- import 'nprogress/nprogress.css'
- import getPageTitle from '@/utils/getPageTitle'
- import { RouterRowTy } from '~/router'
- import { useUserStore } from '@/store/user'
- import { usePermissionStore } from '@/store/permission'
- const whiteList = ['/login', '/404', '/401'] // no redirect whitelist
- router.beforeEach(async (to: any, from, next: any) => {
- // start progress bar
- if (settings.isNeedNprogress) NProgress.start()
- // set page title
- document.title = getPageTitle(to.meta.title)
- if (!settings.isNeedLogin) setToken(TokenKey, settings.tmpToken)
- const hasToken: string | null = getToken(TokenKey)
- const userStore = useUserStore()
- const permissionStore = usePermissionStore()
- if (hasToken) {
- if (to.path === '/login') {
- // if is logged in, redirect to the home page
- next({ path: '/' })
- } else {
- //judge isGetUserInfo
- const isGetUserInfo: boolean = permissionStore.isGetUserInfo
- if (isGetUserInfo) {
- next()
- } else {
- try {
- let accessRoutes: any = []
- if (settings.isNeedLogin) {
- // get user info
- // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
- const { roles }: any = await userStore.getInfo()
- accessRoutes = await permissionStore.generateRoutes(roles)
- } else {
- accessRoutes = asyncRoutes
- }
- // setting constRouters and accessRoutes to vuex , in order to sideBar for using
- permissionStore.M_routes(accessRoutes)
- // dynamically add accessible routes
- //router4 addRoutes destroyed
- accessRoutes.forEach((route: RouterRowTy) => {
- if (route.path === '/dashboard') {
- const childRoute = route.children![0]
- childRoute.redirect = childRoute.children?.length
- ? childRoute.children[0].path
- : '/404'
- }
- router.addRoute(route)
- })
- //already get userInfo
- permissionStore.M_isGetUserInfo(true)
- // hack method to ensure that addRoutes is complete
- // set the replace: true, so the navigation will not leave a history record
- next({ ...to, replace: true })
- } catch (err) {
- await userStore.resetState()
- next(`/login?redirect=${to.path}`)
- if (settings.isNeedNprogress) NProgress.done()
- }
- }
- }
- } else {
- if (whiteList.indexOf(to.path) !== -1) {
- next()
- } else {
- next(`/login?redirect=${to.path}`)
- if (settings.isNeedNprogress) NProgress.done()
- }
- }
- })
- router.afterEach(() => {
- if (settings.isNeedNprogress) NProgress.done()
- })
|