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

66 lines
2.3 KiB
TypeScript

// /middleware/auth.global.ts
export default defineNuxtRouteMiddleware(async (to) => {
const { isAuthenticated, initialized, updateUser } = useAuth();
const { visitCalled } = useVisitTracker();
const api = useApi();
// Helper function to wait for auth initialization, with a timeout.
const waitForAuth = () => {
return new Promise((resolve) => {
// If already initialized, resolve immediately.
if (initialized.value) {
return resolve(true);
}
// Set a timeout to prevent waiting indefinitely
const timeout = setTimeout(() => {
console.warn('[Auth Middleware] Waited 5 seconds for auth, but it did not initialize. Proceeding anyway.');
unwatch();
resolve(false);
}, 5000);
// Watch for the initialized value to change to true.
const unwatch = watch(initialized, (newValue) => {
if (newValue) {
clearTimeout(timeout);
unwatch();
resolve(true);
}
});
});
};
// Only run the waiting logic on the client-side
if (process.client) {
await waitForAuth();
} else if (!initialized.value) {
// On the server, if not initialized, we cannot wait.
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 {
console.log('[Auth Middleware] User is authenticated, triggering daily visit registration.');
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 });
}
});