2021-02-18 18:14:45 +08:00
|
|
|
import router from './router'
|
|
|
|
import store from './store'
|
|
|
|
import NProgress from 'nprogress'
|
2021-02-19 14:34:46 +08:00
|
|
|
import { getToken } from '@/utils/token'
|
2021-02-18 18:14:45 +08:00
|
|
|
import 'nprogress/nprogress.css'
|
|
|
|
|
|
|
|
NProgress.configure({showSpinner: false}) // NProgress Configuration
|
|
|
|
|
|
|
|
const whiteList = ['/login'] // no redirect whitelist
|
|
|
|
|
|
|
|
const generateRoutes = async (to, from, next) => {
|
|
|
|
const hasRoles = store.getters.roles && store.getters.roles.length > 0
|
|
|
|
if (hasRoles) {
|
|
|
|
next()
|
|
|
|
} else {
|
|
|
|
try {
|
2021-02-19 17:05:11 +08:00
|
|
|
const {roles} = await store.dispatch('user/getCurrentUser')
|
2021-02-18 18:14:45 +08:00
|
|
|
const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
|
|
|
|
router.addRoutes(accessRoutes)
|
|
|
|
next({...to, replace: true})
|
|
|
|
} catch (error) {
|
2021-02-19 17:05:11 +08:00
|
|
|
await store.dispatch('user/logout')
|
2021-02-18 18:14:45 +08:00
|
|
|
next(`/login?redirect=${to.path}`)
|
|
|
|
NProgress.done()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 路由前置钩子,根据实际需求修改
|
|
|
|
router.beforeEach(async (to, from, next) => {
|
|
|
|
NProgress.start()
|
2021-02-19 14:34:46 +08:00
|
|
|
const hasToken = getToken()
|
|
|
|
if (hasToken) {
|
2021-02-18 18:14:45 +08:00
|
|
|
if (to.path === '/login') {
|
|
|
|
next({path: '/'})
|
|
|
|
NProgress.done()
|
|
|
|
} else {
|
|
|
|
await generateRoutes(to, from, next)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
/* has not login*/
|
|
|
|
if (whiteList.indexOf(to.path) !== -1) {
|
|
|
|
// in the free login whitelist, go directly
|
|
|
|
next()
|
|
|
|
} else {
|
|
|
|
// other pages that do not have permission to access are redirected to the login page.
|
|
|
|
next(`/login?redirect=${to.path}`)
|
|
|
|
NProgress.done()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
router.afterEach(() => {
|
|
|
|
// finish progress bar
|
|
|
|
NProgress.done()
|
|
|
|
})
|