permissionGuard.ts 2.35 KB
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
    console.log(token)

    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()
    }

  })
}