init.server.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 runtimeConfig = useRuntimeConfig()
  11. const { redirectToLogout } = useRedirect()
  12. const bearer: CookieRef<string | null> = useCookie('BEARER') ?? null
  13. const accessCookieId: CookieRef<string | null> = useCookie('AccessId') ?? null
  14. const switchCookieId: CookieRef<string | null> =
  15. useCookie('SwitchAccessId') ?? null
  16. if (accessCookieId.value === null || Number.isNaN(accessCookieId.value)) {
  17. if (runtimeConfig.public.env === 'production') {
  18. redirectToLogout()
  19. } else {
  20. console.error('Missing access id')
  21. }
  22. return
  23. }
  24. const accessId: number = parseInt(accessCookieId.value)
  25. if (isNaN(accessId)) {
  26. if (runtimeConfig.public.env === 'production') {
  27. redirectToLogout()
  28. } else {
  29. console.error('Invalid access id')
  30. }
  31. return
  32. }
  33. let switchId: number | null = parseInt(switchCookieId.value ?? '')
  34. if (isNaN(switchId)) {
  35. switchId = null
  36. }
  37. const { initiateProfile } = useRefreshProfile()
  38. try {
  39. await initiateProfile(accessId, bearer.value ?? '', switchId)
  40. } catch (error) {
  41. if (
  42. error instanceof UnauthorizedError &&
  43. runtimeConfig.public.env === 'production'
  44. ) {
  45. redirectToLogout()
  46. } else {
  47. throw error
  48. }
  49. }
  50. })