init.server.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import type { CookieRef } from '#app'
  2. import UnauthorizedError from '~/services/error/UnauthorizedError'
  3. import { useRedirect } from '~/composables/utils/useRedirect'
  4. import { useRefreshProfile } from '~/composables/data/useRefreshProfile'
  5. export default defineNuxtPlugin(async () => {
  6. const route = useRoute()
  7. if (route.path.match(/\/public\/.+/)) {
  8. return
  9. }
  10. const { redirectToLogout } = useRedirect()
  11. const bearer: CookieRef<string | null> = useCookie('BEARER') ?? null
  12. const accessCookieId: CookieRef<string | null> = useCookie('AccessId') ?? null
  13. const switchCookieId: CookieRef<string | null> =
  14. useCookie('SwitchAccessId') ?? null
  15. if (accessCookieId.value === null || Number.isNaN(accessCookieId.value)) {
  16. redirectToLogout()
  17. return
  18. }
  19. const accessId: number = parseInt(accessCookieId.value)
  20. if (isNaN(accessId)) {
  21. redirectToLogout()
  22. return
  23. }
  24. let switchId: number | null = parseInt(switchCookieId.value ?? '')
  25. if (isNaN(switchId)) {
  26. switchId = null
  27. }
  28. const { initiateProfile } = useRefreshProfile()
  29. try {
  30. await initiateProfile(accessId, bearer.value ?? '', switchId)
  31. } catch (error) {
  32. if (error instanceof UnauthorizedError) {
  33. redirectToLogout()
  34. } else {
  35. throw error
  36. }
  37. }
  38. })