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;
|
|
|
|
|
|
|
|
|
|
// Check Keycloak auth first
|
2025-06-14 14:50:29 +02:00
|
|
|
const keycloak = useKeycloak();
|
|
|
|
|
|
|
|
|
|
// Initialize Keycloak if not already initialized
|
|
|
|
|
if (!keycloak.isInitialized.value) {
|
|
|
|
|
await keycloak.initKeycloak();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (keycloak.isAuthenticated.value) {
|
2025-06-14 14:09:56 +02:00
|
|
|
// User authenticated with Keycloak
|
|
|
|
|
return;
|
|
|
|
|
}
|
2025-02-16 13:10:19 +01:00
|
|
|
|
2025-06-14 14:09:56 +02:00
|
|
|
// Fall back to Directus auth
|
|
|
|
|
const { fetchUser, setUser } = useDirectusAuth();
|
|
|
|
|
const directusUser = useDirectusUser();
|
|
|
|
|
|
|
|
|
|
if (!directusUser.value) {
|
2025-02-16 13:10:19 +01:00
|
|
|
const user = await fetchUser();
|
|
|
|
|
setUser(user.value);
|
|
|
|
|
}
|
|
|
|
|
|
2025-06-14 14:09:56 +02:00
|
|
|
if (directusUser.value) {
|
|
|
|
|
// User authenticated with Directus
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// No authentication found
|
|
|
|
|
if (isAuthRequired) {
|
|
|
|
|
// Redirect to login page
|
|
|
|
|
return navigateTo('/login');
|
2025-02-16 13:10:19 +01:00
|
|
|
}
|
|
|
|
|
});
|