permissionGuard.ts
2.32 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
import { ProjectRuntimeEnvEnum } from "@/enums/external/envEnum";
import { PageEnum, ShareEnum } from "@/enums/external/pageEnum";
import { useUserStoreWithOut } from "@/store/external/modules/user";
import { NavigationGuardNext, NavigationGuardWithThis, RouteLocationNormalized, RouteLocationRaw, Router } from "vue-router";
const whitePathList: string[] = [PageEnum.BASE_LOGIN, ShareEnum.SHARE_PATH];
const isAloneMode = [ProjectRuntimeEnvEnum.DEV_ALONE, ProjectRuntimeEnvEnum.PROD_ALONE].includes(import.meta.env.MODE as ProjectRuntimeEnvEnum)
const toIotPlatformLogin = ({ to, from, next }: { to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext }) => {
  const { origin, port } = window.location
  if (Number(port) === Number(import.meta.env.VITE_DEV_PORT)) {
    if (to.matched.find(item => whitePathList.includes(item.path))) {
      next()
      return
    } else {
      next(PageEnum.BASE_LOGIN)
    }
    return
  }
  window.location.replace(`${origin}/login?redirect=${import.meta.env.VITE_GLOB_PUBLIC_PATH}`)
}
export function createPermissionGuard(router: Router) {
  const userStore = useUserStoreWithOut()
  router.beforeEach((to, from, next) => {
    if (from.path === '/' &&
      to.path === PageEnum.BASE_HOME &&
      userStore.getUserInfo.homePath &&
      userStore.getUserInfo.homePath !== PageEnum.BASE_HOME
    ) {
      next(userStore.getUserInfo.homePath)
      return
    }
    const token = userStore.getJwtToken
    if (to.matched.find(item => whitePathList.includes(item.path))) {
      if (to.path === PageEnum.BASE_LOGIN && token) {
        const isSessionTimeout = userStore.getSessionTimeout
        try {
          if (isSessionTimeout) {
            next('/')
          }
        } catch (error) {
          console.error(error)
        }
      } else if (to.matched.find(item => ShareEnum.SHARE_PATH)) {
        next()
        return
      }
      else {
        if (!isAloneMode) {
          toIotPlatformLogin({ to, from, next })
          return
        }
        next()
        return
      }
    }
    if (!token) {
      const redirectData = {
        path: PageEnum.BASE_LOGIN,
        redirect: true
      } as RouteLocationRaw
      if (!isAloneMode) {
        toIotPlatformLogin({ to, from, next })
        return
      }
      next(redirectData)
    } else {
      next()
    }
  })
}