init.server.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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> =
  10. useCookie('SwitchAccessId') ?? null
  11. if (accessCookieId.value === null || Number.isNaN(accessCookieId.value)) {
  12. redirectToLogout()
  13. return
  14. }
  15. const accessId: number = parseInt(accessCookieId.value)
  16. if (isNaN(accessId)) {
  17. redirectToLogout()
  18. return
  19. }
  20. let switchId: number | null = parseInt(switchCookieId.value ?? '')
  21. if (isNaN(switchId)) {
  22. switchId = null
  23. }
  24. const { initiateProfile } = useRefreshProfile()
  25. try {
  26. await initiateProfile(accessId, bearer.value ?? '', switchId)
  27. } catch (error) {
  28. if (error instanceof UnauthorizedError) {
  29. redirectToLogout()
  30. } else {
  31. throw error
  32. }
  33. }
  34. })