2025-06-14 14:09:56 +02:00
|
|
|
export default defineNuxtRouteMiddleware(async (to) => {
|
|
|
|
|
// Skip auth for SSR
|
|
|
|
|
if (import.meta.server) return;
|
2025-02-16 13:10:19 +01:00
|
|
|
|
2025-06-14 14:09:56 +02:00
|
|
|
// Check if auth is required (default true unless explicitly set to false)
|
|
|
|
|
const isAuthRequired = to.meta.auth !== false;
|
|
|
|
|
|
2025-06-14 15:58:03 +02:00
|
|
|
if (!isAuthRequired) {
|
2025-06-15 17:37:14 +02:00
|
|
|
console.log('[MIDDLEWARE] Auth not required for route:', to.path);
|
2025-06-14 15:58:03 +02:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2025-06-15 17:37:14 +02:00
|
|
|
console.log('[MIDDLEWARE] Checking authentication for route:', to.path);
|
|
|
|
|
|
2025-06-14 15:01:45 +02:00
|
|
|
try {
|
2025-06-15 17:37:14 +02:00
|
|
|
// Check Keycloak authentication via session API
|
|
|
|
|
const sessionData = await $fetch('/api/auth/session') as any;
|
2025-06-14 15:01:45 +02:00
|
|
|
|
2025-06-15 17:37:14 +02:00
|
|
|
console.log('[MIDDLEWARE] Session check result:', {
|
|
|
|
|
authenticated: sessionData.authenticated,
|
|
|
|
|
hasUser: !!sessionData.user,
|
|
|
|
|
userId: sessionData.user?.id
|
|
|
|
|
});
|
2025-02-16 13:10:19 +01:00
|
|
|
|
2025-06-15 17:37:14 +02:00
|
|
|
if (sessionData.authenticated && sessionData.user) {
|
|
|
|
|
console.log('[MIDDLEWARE] User authenticated, allowing access');
|
2025-06-14 15:01:45 +02:00
|
|
|
return;
|
|
|
|
|
}
|
2025-02-16 13:10:19 +01:00
|
|
|
|
2025-06-15 17:37:14 +02:00
|
|
|
console.log('[MIDDLEWARE] No valid authentication found, redirecting to login');
|
2025-06-14 15:58:03 +02:00
|
|
|
return navigateTo('/login');
|
|
|
|
|
|
2025-06-14 15:01:45 +02:00
|
|
|
} catch (error) {
|
2025-06-15 17:37:14 +02:00
|
|
|
console.error('[MIDDLEWARE] Auth check failed:', error);
|
2025-06-14 15:58:03 +02:00
|
|
|
return navigateTo('/login');
|
2025-02-16 13:10:19 +01:00
|
|
|
}
|
|
|
|
|
});
|