Checking authorization when the page is reloaded

22 Views Asked by At

The application uses middleware to verify user authorization. The JWT token for authorization is stored in cookies. When the application is loaded, the user's data is stored in the pinia storage, and the protected paths are displayed correctly during authorization, including after the page is reloaded. However, if the application is created via "generate", then when the page is reloaded, there is a constant redirection, since user data is not available in the storage. If you are using an already downloaded application, then everything works correctly. At the same time, if you reload on dynamic pages [id].vue, then everything also works.

middleware/auth.js

import { useGlobalStore } from "@/stores/global"
const store = useGlobalStore()
export default defineNuxtRouteMiddleware(async (to, from) => {
    if (!store.person) {
    await store.getUserPerson()
  }
  if (!store.is_auth) {
    return navigateTo("/", { replace: true })
  }
})

storage

export const useGlobalStore = defineStore("global", () => {
  const is_staff = ref(false)
  const is_auth = ref(false)
  const person = ref()
  const getUserPerson = async () => {
    if (process.client) {
      await myFetch("/auth/users/me/") //$fetch
        .then((res) => {
          person.value = res
          if (res.access_date) {
            is_auth.value = true
          }
          is_staff.value = res.is_staff
        })
        .catch(() => {})
    } else {
      try {
        const { data: persons, error } = await useMyFetch("/auth/users/me/") //useFetch
        if (persons && persons.value) {
          person.value = persons.value
          if (persons.value.access_date) {
            is_auth.value = true
          }
          is_staff.value = persons.value.is_staff
        }
      } catch (e) {}
    }
  }
  })

I still can't figure out what the problem might be... If someone has come across this issue and found a solution, please share.

0

There are 0 best solutions below