Blame view

src/router/guard/permissionGuard.ts 2.02 KB
陈文彬 authored
1
2
import type { Router, RouteRecordRaw } from 'vue-router';
3
import { usePermissionStoreWithOut } from '/@/store/modules/permission';
vben authored
4
陈文彬 authored
5
import { PageEnum } from '/@/enums/pageEnum';
6
import { useUserStoreWithOut } from '/@/store/modules/user';
vben authored
7
8
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
陈文彬 authored
9
10
11
12
13
14

const LOGIN_PATH = PageEnum.BASE_LOGIN;

const whitePathList: PageEnum[] = [LOGIN_PATH];

export function createPermissionGuard(router: Router) {
15
16
  const userStore = useUserStoreWithOut();
  const permissionStore = usePermissionStoreWithOut();
陈文彬 authored
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
30
    const token = userStore.getToken;
陈文彬 authored
31
32
33
34

    // token does not exist
    if (!token) {
      // You can access without permission. You need to set the routing meta.ignoreAuth to true
35
      if (to.meta.ignoreAuth) {
陈文彬 authored
36
37
38
        next();
        return;
      }
39
陈文彬 authored
40
      // redirect login page
Vben authored
41
      const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
42
43
44
45
46
47
48
49
50
51
        path: LOGIN_PATH,
        replace: true,
      };
      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path,
        };
      }
      next(redirectData);
陈文彬 authored
52
53
      return;
    }
54
Vben authored
55
    if (permissionStore.getIsDynamicAddedRoute) {
陈文彬 authored
56
57
58
      next();
      return;
    }
59
陈文彬 authored
60
    const routes = await permissionStore.buildRoutesAction();
vben authored
61
陈文彬 authored
62
    routes.forEach((route) => {
Vben authored
63
      router.addRoute(route as unknown as RouteRecordRaw);
陈文彬 authored
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
69
    permissionStore.setDynamicAddedRoute(true);
陈文彬 authored
70
71
72
    next(nextData);
  });
}