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:01:45 +02:00
|
|
|
try {
|
2025-06-14 15:26:26 +02:00
|
|
|
// Check Directus auth first (most reliable)
|
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-14 15:07:41 +02:00
|
|
|
// Ignore directus auth errors for public pages
|
|
|
|
|
if (!isAuthRequired) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
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-14 15:26:26 +02:00
|
|
|
// Check Keycloak auth if authentication is required
|
|
|
|
|
if (isAuthRequired) {
|
|
|
|
|
const keycloak = useKeycloak();
|
|
|
|
|
|
|
|
|
|
// Initialize Keycloak if not already done
|
|
|
|
|
if (!keycloak.isInitialized.value) {
|
|
|
|
|
try {
|
|
|
|
|
const authenticated = await keycloak.initKeycloak();
|
|
|
|
|
if (authenticated) {
|
|
|
|
|
// User authenticated with Keycloak
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Keycloak initialization failed:', error);
|
|
|
|
|
// Continue to login redirect
|
|
|
|
|
}
|
|
|
|
|
} else if (keycloak.isAuthenticated.value) {
|
|
|
|
|
// User already authenticated with Keycloak
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-06-14 15:01:45 +02:00
|
|
|
// No authentication found
|
|
|
|
|
if (isAuthRequired) {
|
|
|
|
|
// Redirect to login page
|
|
|
|
|
return navigateTo('/login');
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Auth middleware error:', error);
|
|
|
|
|
if (isAuthRequired) {
|
|
|
|
|
return navigateTo('/login');
|
|
|
|
|
}
|
2025-02-16 13:10:19 +01:00
|
|
|
}
|
|
|
|
|
});
|