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) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2025-06-14 15:01:45 +02:00
|
|
|
try {
|
2025-06-14 15:58:03 +02:00
|
|
|
// Check Directus auth first
|
2025-06-14 15:01:45 +02:00
|
|
|
const { fetchUser, setUser } = useDirectusAuth();
|
|
|
|
|
const directusUser = useDirectusUser();
|
|
|
|
|
|
|
|
|
|
if (!directusUser.value) {
|
|
|
|
|
try {
|
|
|
|
|
const user = await fetchUser();
|
|
|
|
|
setUser(user.value);
|
|
|
|
|
} catch (error) {
|
2025-06-15 15:47:36 +02:00
|
|
|
// Directus auth failed, continue to check custom Keycloak auth
|
2025-06-14 15:01:45 +02:00
|
|
|
}
|
|
|
|
|
}
|
2025-02-16 13:10:19 +01:00
|
|
|
|
2025-06-14 15:01:45 +02:00
|
|
|
if (directusUser.value) {
|
|
|
|
|
// User authenticated with Directus
|
|
|
|
|
return;
|
|
|
|
|
}
|
2025-02-16 13:10:19 +01:00
|
|
|
|
2025-06-15 15:47:36 +02:00
|
|
|
// Check custom Keycloak auth via session API
|
|
|
|
|
try {
|
|
|
|
|
const sessionData = await $fetch('/api/auth/session') as any;
|
|
|
|
|
if (sessionData.authenticated && sessionData.user) {
|
|
|
|
|
// User authenticated with Keycloak
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
// Session check failed, continue to redirect
|
2025-06-14 15:26:26 +02:00
|
|
|
}
|
|
|
|
|
|
2025-06-14 15:58:03 +02:00
|
|
|
// No authentication found, redirect to login
|
|
|
|
|
return navigateTo('/login');
|
|
|
|
|
|
2025-06-14 15:01:45 +02:00
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Auth middleware error:', error);
|
2025-06-14 15:58:03 +02:00
|
|
|
return navigateTo('/login');
|
2025-02-16 13:10:19 +01:00
|
|
|
}
|
|
|
|
|
});
|