permission.js
2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import usePermissionStore from '@/store/modules/permission'
import useSettingsStore from '@/store/modules/settings'
import useUserStore from '@/store/modules/user'
import { getToken,setToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'
import { isHttp } from '@/utils/validate'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from './router'
NProgress.configure({ showSpinner: false });
const whiteList = ['/login', '/register','/in','/home/index','/getInfo'];
router.beforeEach((to, from, next) => {
NProgress.start()
if (getToken()) {
to.meta.title && useSettingsStore().setTitle(to.meta.title)
/* has token*/
if (to.path === '/login') {
next({ path: '/' }) // m没有token
NProgress.done()
} else {
if (useUserStore().roles.length === 0) {
isRelogin.show = true
// 判断当前用户是否已拉取完user_info信息
useUserStore().getInfo().then(() => {
isRelogin.show = false
usePermissionStore().generateRoutes().then(accessRoutes => {
// 根据roles权限生成可访问的路由表
accessRoutes.forEach(route => {
if (!isHttp(route.path)) {
router.addRoute(route) // 动态添加可访问路由表
}
})
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
})
}).catch(err => {
// useUserStore().logOut().then(() => {
// ElMessage.error(err)
// next({ path: '/' })
// })
useUserStore().logOut().then(() => {
// Message.error(err)
// next({ path: '/' })
let index = to.path.indexOf("?");
let length = to.path.length;
let param = to.path.substring(index,length);
location.href = '/';
})
})
} else {
next()
}
}
} else {
// 没有token
if (whiteList.indexOf(to.path) !== -1) {
// 在免登录白名单,直接进入
next()
} else {
let params = getURLParams1();
let url = null;
if(params && params.token){
setToken(params.token)
url = "/?token="+params.token;
}else{
url = `${to.fullPath}`;
if(url.indexOf("redirect") == -1){
if(url.indexOf(url,"?") > -1){
url =url.replace("?", "&");
}
url = `/login?redirect=`+url;
}else{
url = `/login`+url;
}
}
next(url) // 否则全部重定向到登录页
NProgress.done()
}
}
})
function getURLParams1() {
const searchParams = window.location.search.substring(1).split('&');
const params = {
};
for (const param of searchParams) {
const [key, value] = param.split('=');
params[key] = value;
}
return params;
}
router.afterEach(() => {
NProgress.done()
})