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

[Feature] Guest-mode for global middleware #82

Closed jialeee17 closed 5 months ago

jialeee17 commented 5 months ago

On my website, all pages should only be able to accessed by authenticated except the "Login" & Register" page. Therefore, I enabled the global middleware to prevent unauthenticated user to access the other pages on my website.

At the same time, I want to prevent authenticated user from accessing the "Login" & Register" page. What I did was I tried exclude the "Register" page from the global middleware by adding the excludeFromSanctum: true & middleware: ['sanctum:guest'] in my "Register" page. Therefore, my current solution is to manually apply the middleware to each page...

Then, I got the 500 error saying "Unknown route middleware: 'sanctum:guest'. Valid middleware: .". Is it considered a bug?

manchenkoff commented 5 months ago

Hey @jialeee17, thanks for detailed question.

The module works in only one mode or another. When you enable global middleware, it disables local middlewares (as mentioned here) to avoid potential conflicts in their behavior. However, only login page was excluded for authenticated access by design.

Right now, there is no way of setting more pages with "guest-only" access, but I'll try to introduce this feature this week.

In the meantime, I would suggest using simple local middleware in your register page like this

<script setup lang="ts">
definePageMeta({
  middleware: [
    function (to, from) {
      const { isAuthenticated } = useSanctumAuth();

      if (isAuthenticated) {
        return navigateTo('/');
      }
    },
  ],
});
</script>

I'll let you know once new feature is available 👍

manchenkoff commented 5 months ago

Hey @jialeee17, the package was published with v0.3.0 version, please try to upgrade and check this documentation section to migrate to the new configuration