Files
veridian/app/middleware/auth.global.ts
T

55 lines
2.0 KiB
TypeScript

export default defineNuxtRouteMiddleware(async (to) => {
const { session: rawSession, fetchSession } = useAuth();
let session = rawSession.value;
const isAuthPage = to.path.toLowerCase().includes("/auth/");
// Only fetch session if not on auth pages (prevents race condition after logout)
if (!rawSession.value && !isAuthPage) {
const result = await fetchSession();
if (result.ok) {
session = result.data.session;
} else {
console.error("Failed to fetch session:", result.error);
session = null;
}
}
const loggedIn = computed(() => !!session);
// if authenticated, and on a signin/signup page, redirect to home page
if (isAuthPage && loggedIn.value) {
return await navigateTo((to.query.to as string) ?? "/");
}
// A fresh instance has no accounts, so there is nothing to log in to yet
// and the first visitor creates the admin account instead.
if (!loggedIn.value) {
const setupNeeded = useState<boolean | null>('instance:setupNeeded', () => null);
const isSetupPage = to.path.toLowerCase() === '/auth/setup';
// once an account exists the answer never changes back
if (setupNeeded.value !== false) {
try {
setupNeeded.value = (await $fetch<{ setupNeeded: boolean }>('/api/instance')).setupNeeded;
} catch (error) {
console.error('Failed to check instance setup:', error);
setupNeeded.value = null;
}
}
if (setupNeeded.value === true && !isSetupPage) {
return await navigateTo('/auth/setup');
}
if (setupNeeded.value !== true && isSetupPage) {
return await navigateTo('/auth/login');
}
}
// If not authenticated, and not on a signin/signup page, redirect to login page
if (!loggedIn.value && !isAuthPage) {
return await navigateTo(`/auth/login?to=${to.path}`);
}
});