Blame view

src/router/guard/permissionGuard.ts 2.09 KB
陈文彬 authored
1
2
import type { Router, RouteRecordRaw } from 'vue-router';
Vben authored
3
import { usePermissionStoreWidthOut } from '/@/store/modules/permission';
vben authored
4
陈文彬 authored
5
import { PageEnum } from '/@/enums/pageEnum';
Vben authored
6
import { useUserStoreWidthOut } 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) {
Vben authored
15
16
  const userStore = useUserStoreWidthOut();
  const permissionStore = usePermissionStoreWidthOut();
陈文彬 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
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
43
      const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
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);
陈文彬 authored
54
55
      return;
    }
Vben authored
56
    if (permissionStore.getIsDynamicAddedRoute) {
陈文彬 authored
57
58
59
60
      next();
      return;
    }
    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);
  });
}