habits.andr33v.ru/middleware/auth.global.ts

17 lines
753 B
TypeScript

// /middleware/auth.ts
export default defineNuxtRouteMiddleware((to) => {
// `app.vue` is responsible for the initial fetchUser call.
// This middleware just reads the state that's already present.
const { isAuthenticated } = useAuth();
// if the user is authenticated and tries to access /login, redirect to home
if (isAuthenticated.value && to.path === '/login') {
return navigateTo('/', { replace: true });
}
// if the user is not authenticated and tries to access any page other than public routes, redirect to /login
const publicRoutes = ['/login', '/register']; // Add any other public paths here
if (!isAuthenticated.value && !publicRoutes.includes(to.path)) {
return navigateTo('/login', { replace: true });
}
});