manchenkoff / nuxt-auth-sanctum

Nuxt module for Laravel Sanctum authentication
https://manchenkoff.gitbook.io/nuxt-auth-sanctum/
MIT License
153 stars 18 forks source link

useSanctumUser not returning user data immediately after login but only after Hard reload #96

Closed Scarwolf closed 4 months ago

Scarwolf commented 4 months ago

My flow is like this:

User log's in:

const { login } = useSanctumAuth();
 await login(event.data)

After this I redirect to the main page. Now if you navigate around, and want to go to a certain page that requires authentication and tries to display your username, its not working at first. TypeError: Cannot read properties of null (reading 'firstName')

This comes from a custom composable useAuthUser I created:

export const useAuthUser = () => {
  const sanctumAuth = useSanctumAuth();
  const sanctumUser = useSanctumUser<UserModel>();

 const userObject = computed(() => {
   return sanctumUser.value === null
    ? null
    : sanctumUser.value.data;
 });

  const isAuthenticated = ref(sanctumAuth.isAuthenticated);

  const firstName = computed(() => {
    if (!unref(userObject)) {
      return null;
    }

    return unref(userObject)?.invoiceAddress?.firstName ?? null;
  });
}

If I use the following in a component:

const auth = useAuthUser();
console.log(auth.firstName.value)

it willl throw null at first, until I do a hard refresh.

Any idea what i'm doing wrong? I'm fairly new to Vue 3, so it could also be related to me doing something wrong using the composition API.

manchenkoff commented 4 months ago

Hey @Scarwolf! I'm not sure if your code might affect the behavior, but it should work fine with the default configuration.

You can check the code of the profile page in the playground, it does almost the same thing you wanted - show identity details only for authenticated users. It is done by using sanctum:auth middleware in the page meta, thus you can guarantee that guests will be prevented from accessing it.

As for hard refresh, it shouldn't be a problem since after successful login the module refreshes the user identity in the state and propagates it to all references due to reactivity.

So, I suggest using proper middleware for your page and trying to use useSanctumUser composable directly instead of your useAuthUser implementation to make sure that it is not a problem related to the package.

Let me know if it helps.

manchenkoff commented 4 months ago

Closing due to inactivity, feel free to re-open