64 lines
1.7 KiB
TypeScript
64 lines
1.7 KiB
TypeScript
export default defineNuxtRouteMiddleware(async (to) => {
|
|
// Skip auth for SSR
|
|
if (import.meta.server) return;
|
|
|
|
// Check if auth is required (default true unless explicitly set to false)
|
|
const isAuthRequired = to.meta.auth !== false;
|
|
|
|
try {
|
|
// Check Directus auth first (most reliable)
|
|
const { fetchUser, setUser } = useDirectusAuth();
|
|
const directusUser = useDirectusUser();
|
|
|
|
if (!directusUser.value) {
|
|
try {
|
|
const user = await fetchUser();
|
|
setUser(user.value);
|
|
} catch (error) {
|
|
// Ignore directus auth errors for public pages
|
|
if (!isAuthRequired) {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (directusUser.value) {
|
|
// User authenticated with Directus
|
|
return;
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
}
|
|
|
|
// 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');
|
|
}
|
|
}
|
|
});
|