auth.global.ts 1.38 KB
import { FORBIDDEN_PATH, LOGIN_PATH, canAccessPageByRoles, isPublicPath, normalizePagePath } from '~/utils/permission'
import { resolvePostLoginPath } from '~/utils/post-login'

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 = normalizePagePath(to.path)
  const isLoginPage = normalizedPath === LOGIN_PATH

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

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

    if (token.value) {
      const roles = Array.isArray(user.value?.roles) ? user.value.roles : []
      return navigateTo(resolvePostLoginPath(to.query.redirect, roles))
    }

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