permissionGuard.ts 1.72 KB
import { RuntimeEnvironment } from "@/enums/external/envEnum";
import { PageEnum } from "@/enums/pageEnum";
import { useUserStoreWithOut } from "@/store/external/module/user";
import { RouteLocationRaw, Router } from "vue-router";


const whitePathList: string[] = [PageEnum.BASE_LOGIN];

const isIndependenceMode = import.meta.env.MODE === RuntimeEnvironment.INDEPENDENCE

const toIotPlatformLogin = () => {
  const { origin } = window.location
  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
    ) {
      console.log(userStore.getUserInfo.homePath)
      next(userStore.getUserInfo.homePath)
      return
    }

    const token = userStore.getJwtToken

    if (whitePathList.includes(to.path)) {
      if (to.path === PageEnum.BASE_LOGIN && token) {
        const isSessionTimeout = userStore.getSessionTimeout
        try {
          if (!isSessionTimeout) {
            next('/')
          }
        } catch (error) {
          console.error(error)
        }
      }
      else {
        if (isIndependenceMode) {
          toIotPlatformLogin()
          return
        }
        next()
        return
      }
    }

    if (!token) {
      const redirectData = {
        path: PageEnum.BASE_LOGIN,
        redirect: true
      } as RouteLocationRaw
      if (isIndependenceMode) {
        toIotPlatformLogin()
        return
      }
      next(redirectData)
    } else {
      next()
    }

  })
}