init.server.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 { redirectToLogout } = useRedirect()
  7. const bearer: CookieRef<string | null> = useCookie('BEARER') ?? null
  8. const accessCookieId: CookieRef<string | null> = useCookie('AccessId') ?? null
  9. const switchCookieId: CookieRef<string | null> = useCookie('SwitchAccessId') ?? null
  10. if (accessCookieId.value === null || Number.isNaN(accessCookieId.value)) {
  11. redirectToLogout()
  12. return
  13. }
  14. const accessId: number = parseInt(accessCookieId.value)
  15. if (isNaN(accessId)) {
  16. redirectToLogout()
  17. return
  18. }
  19. let switchId = null
  20. if (switchCookieId.value !== null && typeof switchCookieId.value !== 'undefined') {
  21. if (!isNaN(switchId)) {
  22. switchId = parseInt(switchCookieId.value)
  23. } else {
  24. console.error('Invalid switch id : ' + switchCookieId.value)
  25. }
  26. }
  27. const { initiateProfile } = useRefreshProfile()
  28. try {
  29. await initiateProfile(
  30. accessId,
  31. bearer.value ?? '',
  32. switchId,
  33. )
  34. } catch (error) {
  35. if (error instanceof UnauthorizedError) {
  36. redirectToLogout()
  37. } else {
  38. throw error
  39. }
  40. }
  41. })