108 lines
3.1 KiB
JavaScript
108 lines
3.1 KiB
JavaScript
import router from './router'
|
|
import { checkToken,logout } from '@/api/login'
|
|
import store from './store'
|
|
import { Message } from 'element-ui'
|
|
import NProgress from 'nprogress'
|
|
import 'nprogress/nprogress.css'
|
|
import { getToken,removeToken } from '@/utils/auth'
|
|
import { isRelogin } from '@/utils/request'
|
|
import getPageTitle from '@/utils/get-page-title'
|
|
|
|
NProgress.configure({ showSpinner: false })
|
|
|
|
const whiteList = ['/login', '/auth-redirect', '/bind', '/register','/tools','/loginBySSO','/queryTraceInfo','/onlineChat']
|
|
|
|
router.beforeEach(async(to, from, next) => {
|
|
NProgress.start()
|
|
if (to.query.token) {
|
|
setToken(to.query.token)
|
|
}
|
|
if (to.query.referrer) {
|
|
Cookies.set('referrer', to.query.referrer)
|
|
}
|
|
document.title = getPageTitle(to.meta.i18n ? i18n.t('router.title.' + to.meta.title) : to.meta.title)
|
|
const hasToken = getToken()
|
|
if (hasToken) {
|
|
to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
|
|
|
|
/* has token*/
|
|
if (to.path === '/login') {
|
|
next({ path: '/' })
|
|
NProgress.done()
|
|
} else {
|
|
|
|
// 获取最近访问路径
|
|
// store.dispatch('tagsView/setTitle')
|
|
|
|
if (store.getters.roles.length === 0) {
|
|
|
|
isRelogin.show = true
|
|
// 判断当前用户是否已拉取完user_info信息
|
|
store.dispatch('GetInfo').then(() => {
|
|
isRelogin.show = false
|
|
store.dispatch('GenerateRoutes').then(accessRoutes => {
|
|
// 根据roles权限生成可访问的路由表
|
|
let path = '/'
|
|
if(accessRoutes&&accessRoutes[0].path != path){
|
|
if(accessRoutes[0].children){
|
|
path = accessRoutes[0].path + '/' + accessRoutes[0].children[0].path
|
|
}
|
|
else{
|
|
path = accessRoutes[0].path
|
|
}
|
|
}else{
|
|
path = accessRoutes[0].children[0].path
|
|
}
|
|
// next({ path, replace: true }) // hack方法 确保addRoutes已完成
|
|
// next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
|
|
router.addRoutes(accessRoutes) // 动态添加可访问路由表
|
|
|
|
if(from.path == '/login' || to.fullPath=='/'){
|
|
next({ path, replace: true }) // hack方法 确保addRoutes已完成
|
|
}
|
|
else{
|
|
next({ ...to, replace: true })
|
|
}
|
|
|
|
})
|
|
}).catch(err => {
|
|
store.dispatch('LogOut').then(() => {
|
|
Message.error(err)
|
|
next({ path: '/' })
|
|
})
|
|
})
|
|
} else {
|
|
|
|
// next()
|
|
|
|
// 判断token有效性
|
|
checkToken().then(res => {
|
|
next()
|
|
}).catch((err) => {
|
|
logout().then(() => {
|
|
Message.error(err || '已成功退出')
|
|
removeToken()
|
|
next({
|
|
path: '/'
|
|
})
|
|
})
|
|
})
|
|
|
|
}
|
|
}
|
|
} else {
|
|
// 没有token
|
|
if (whiteList.indexOf(to.path) !== -1) {
|
|
// 在免登录白名单,直接进入
|
|
next()
|
|
} else {
|
|
next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
|
|
NProgress.done()
|
|
}
|
|
}
|
|
})
|
|
|
|
router.afterEach(() => {
|
|
NProgress.done()
|
|
})
|