export default defineNuxtRouteMiddleware(async (to) => { // Skip on server-side rendering if (import.meta.server) return; // Skip if no auth requirements or roles specified if (!to.meta.roles) { return; } console.log('[AUTHORIZATION] Checking route access for:', to.path, 'Required roles:', to.meta.roles); try { // Get auth state from authentication middleware (already cached) const nuxtApp = useNuxtApp(); const authState = nuxtApp.payload?.data?.authState; // If auth state not available, authentication middleware hasn't run or failed if (!authState || !authState.authenticated || !authState.user) { console.log('[AUTHORIZATION] No auth state found from authentication middleware'); // Try to get from session cache as fallback const sessionCache = nuxtApp.payload?.data?.['auth:session:cache']; if (!sessionCache || !sessionCache.authenticated) { console.log('[AUTHORIZATION] User not authenticated, redirecting to login'); return navigateTo('/login'); } // Use cached session authState.user = sessionCache.user; authState.groups = sessionCache.groups || []; } // Get required roles for this route const requiredRoles = Array.isArray(to.meta.roles) ? to.meta.roles : [to.meta.roles]; const userGroups = authState.groups || []; // Check if user has any of the required roles const hasRequiredRole = requiredRoles.some(role => userGroups.includes(role)); if (!hasRequiredRole) { console.log('[AUTHORIZATION] Access denied. User groups:', userGroups, 'Required roles:', requiredRoles); // Store the error in nuxtApp to show toast on redirect nuxtApp.payload.authError = `Access denied. This page requires one of the following roles: ${requiredRoles.join(', ')}`; // Redirect to dashboard instead of login since user is authenticated return navigateTo('/dashboard'); } console.log('[AUTHORIZATION] Access granted for route:', to.path); } catch (error) { console.error('[AUTHORIZATION] Error checking route access:', error); // Don't automatically redirect to login on errors // Let the authentication middleware handle auth failures const toast = useToast(); toast.error('Failed to verify permissions. Please try again.'); return navigateTo('/dashboard'); } });