1
2
import type { Router, RouteRecordRaw } from 'vue-router';
Vben
authored
4 years ago
3
import { usePermissionStoreWidthOut } from '/@/store/modules/permission';
vben
authored
5 years ago
4
5
import { PageEnum } from '/@/enums/pageEnum';
Vben
authored
4 years ago
6
import { useUserStoreWidthOut } from '/@/store/modules/user';
vben
authored
5 years ago
7
Vben
authored
4 years ago
8
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
9
10
11
12
13
14
const LOGIN_PATH = PageEnum.BASE_LOGIN;
const whitePathList: PageEnum[] = [LOGIN_PATH];
export function createPermissionGuard(router: Router) {
Vben
authored
4 years ago
15
16
const userStore = useUserStoreWidthOut();
const permissionStore = usePermissionStoreWidthOut();
17
18
19
20
21
22
23
24
25
26
27
28
29
router.beforeEach(async (to, from, next) => {
// Jump to the 404 page after processing the login
if (from.path === LOGIN_PATH && to.name === PAGE_NOT_FOUND_ROUTE.name) {
next(PageEnum.BASE_HOME);
return;
}
// Whitelist can be directly entered
if (whitePathList.includes(to.path as PageEnum)) {
next();
return;
}
Vben
authored
4 years ago
30
const token = userStore.getToken;
31
32
33
34
35
36
37
38
39
40
41
42
// token does not exist
if (!token) {
// You can access without permission. You need to set the routing meta.ignoreAuth to true
if (
to.meta.ignoreAuth
// || to.name === FULL_PAGE_NOT_FOUND_ROUTE.name
) {
next();
return;
}
// redirect login page
Vben
authored
4 years ago
43
const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
vben
authored
5 years ago
44
45
46
47
48
49
50
51
52
53
path: LOGIN_PATH,
replace: true,
};
if (to.path) {
redirectData.query = {
...redirectData.query,
redirect: to.path,
};
}
next(redirectData);
54
55
return;
}
Vben
authored
4 years ago
56
if (permissionStore.getIsDynamicAddedRoute) {
57
58
59
60
next();
return;
}
const routes = await permissionStore.buildRoutesAction();
vben
authored
4 years ago
61
62
routes.forEach((route) => {
vben
authored
4 years ago
63
router.addRoute((route as unknown) as RouteRecordRaw);
64
65
66
67
68
});
const redirectPath = (from.query.redirect || to.path) as string;
const redirect = decodeURIComponent(redirectPath);
const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
Vben
authored
4 years ago
69
permissionStore.setDynamicAddedRoute(true);
70
71
72
next(nextData);
});
}