permission.js
3.57 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
import router from './router';
import store from './store';
import {
Message
} from 'element-ui';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import {
getToken
} from '@/utils/auth'; // get token from cookie
import {modifyThemeColor, recursiveTreeByLastLevel} from '@/utils';
NProgress.configure({
showSpinner: false
}); // NProgress Configuration
const whiteList = ['/login', '/auth-redirect', '/student/live']; // no redirect whitelist
router.beforeEach(async(to, from, next) => {
// start progress bar
NProgress.start();
// set page title
// document.title = getPageTitle(to.meta.title)
// determine whether the user has logged in
const hasToken = getToken();
if (hasToken) {
if (to.path === '/login') {
// if is logged in, redirect to the home page
next({
path: '/'
});
NProgress.done();
} else {
// determine whether the user has obtained his permission permissions through getInfo
const hasPermissions = store.getters.permissions && store.getters.permissions.length > 0;
if (hasPermissions) {
next();
} else {
try {
// get user info
// note: permissions must be a object array! such as: ['admin'] or ,['developer','editor']
modifyThemeColor('#409EFF', store.getters.theme);
store.dispatch('app/initThemeColorLayout').then(() => {
});
store.dispatch('user/getInfo').then(() => {
});
const accessRoutes = await store.dispatch('permission/generateRoutes');
router.addRoutes(accessRoutes);
// hack method to ensure that addRoutes is complete
// set the replace: true, so the navigation will not leave a history record
if (accessRoutes.length === 0) {
next('/401');
} else if (to.name === 'loading') {
next();
} else {
next({
...to,
replace: true
});
}
} catch (error) {
// remove token and go to login page to re-login
await store.dispatch('user/resetToken');
Message.error(error || 'Has Error');
next(`/login?redirect=${encodeURI(to.fullPath)}`);
NProgress.done();
}
}
}
} else {
/* has no token*/
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=${encodeURI(to.fullPath)}`);
NProgress.done();
}
}
});
router.afterEach((to, from) => {
// finish progress bar
NProgress.done();
let path = to.fullPath;
if (to.meta.activeMenu) {
path = to.meta.activeMenu;
}
const routerList = recursiveTreeByLastLevel(path, store.getters.menus, 'routeUrl');
if (to.meta.activeMenu) {
routerList.push({
id: to.name,
routeUrl: to.fullPath,
name: to.meta.title || to.name
});
}
store.dispatch('permission/setCrumbList', routerList);
});