// /middleware/auth.global.ts export default defineNuxtRouteMiddleware(async (to) => { const { isAuthenticated, initialized, updateUser } = useAuth(); const { visitCalled } = useVisitTracker(); const api = useApi(); // Do not run middleware until auth state is initialized on client-side if (!initialized.value) { return; } // --- Daily Visit Registration --- // This logic runs once per application load on the client-side for authenticated users. if (process.client && isAuthenticated.value && !visitCalled.value) { visitCalled.value = true; // Set flag immediately to prevent race conditions try { const updatedUser = await api('/api/user/visit', { method: 'POST' }); if (updatedUser) { updateUser(updatedUser); } } catch (e) { console.error("Failed to register daily visit from middleware:", e); } } // 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']; if (!isAuthenticated.value && !publicRoutes.includes(to.path)) { return navigateTo('/login', { replace: true }); } });