auth.global.ts 589 B

1234567891011121314151617181920
  1. // Authentication middleware to protect routes
  2. export default defineNuxtRouteMiddleware((to, _from) => {
  3. const { isAuthenticated, isInitialized } = useAuth()
  4. // Check if route requires authentication
  5. // Routes with auth: false in their page meta are public
  6. if (to.meta.auth === false) {
  7. return
  8. }
  9. // If user is not authenticated, redirect to login
  10. if (isInitialized.value && !isAuthenticated.value) {
  11. const redirect = to.fullPath
  12. return navigateTo({
  13. path: '/login',
  14. query: redirect && redirect !== '/login' ? { redirect } : undefined,
  15. })
  16. }
  17. })