init.server.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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: number | null = parseInt(switchCookieId.value ?? '')
  20. if (isNaN(switchId)) {
  21. switchId = null
  22. }
  23. const { initiateProfile } = useRefreshProfile()
  24. try {
  25. await initiateProfile(
  26. accessId,
  27. bearer.value ?? '',
  28. switchId,
  29. )
  30. } catch (error) {
  31. if (error instanceof UnauthorizedError) {
  32. redirectToLogout()
  33. } else {
  34. throw error
  35. }
  36. }
  37. })