auth.global.ts 1.17 KB
import { FORBIDDEN_PATH, LOGIN_PATH, canAccessPageByRoles, isPublicPath } from '~/utils/permission'

function withRedirect(path: string) {
  return `${LOGIN_PATH}?redirect=${encodeURIComponent(path)}`
}

function withForbiddenRedirect(path: string) {
  return `${FORBIDDEN_PATH}?from=${encodeURIComponent(path)}`
}

export default defineNuxtRouteMiddleware(async (to) => {
  const { token, user, fetchCurrentUser } = useAuth()
  const normalizedPath = to.path
  const isLoginPage = normalizedPath === LOGIN_PATH

  if (isLoginPage) {
    if (!token.value) {
      return
    }

    if (!user.value) {
      await fetchCurrentUser()
    }

    if (token.value) {
      return navigateTo('/')
    }

    return
  }

  if (!token.value) {
    return navigateTo(withRedirect(to.fullPath))
  }

  if (!user.value) {
    const currentUser = await fetchCurrentUser()

    if (!currentUser) {
      return navigateTo(withRedirect(to.fullPath))
    }
  }

  if (isPublicPath(normalizedPath)) {
    return
  }

  const roles = Array.isArray(user.value?.roles) ? user.value.roles : []
  if (!canAccessPageByRoles(roles, normalizedPath)) {
    return navigateTo(withForbiddenRedirect(to.fullPath))
  }
})