// middleware/checkPageAccess.ts // Middleware to check if user has access to the page based on hakAkses export default defineNuxtRouteMiddleware(async (to, from) => { // Skip check for public pages const publicPaths = ['/LoginPage', '/auth/login', '/index-legacy']; // index.vue is the debug dashboard, let's keep it accessible for now as requested if (to.path === '/' || publicPaths.includes(to.path)) { return; } // Import useAuth and useHakAkses const { user, checkAuth } = useAuth(); const { getAllowedPages } = useHakAkses(); // If user not loaded, try to load if (!user.value) { await checkAuth(); } // If still not authenticated, redirect to login if (!user.value) { return navigateTo('/LoginPage'); } try { const allowedPages = await getAllowedPages(); // Normalize paths for comparison (optional, but good for robustness) const targetPath = to.path.endsWith('/') && to.path.length > 1 ? to.path.slice(0, -1) : to.path; // Check if user has access to this page // We also check against the raw path just in case const isAllowed = allowedPages.some(path => { const normalizedAllowed = path.endsWith('/') && path.length > 1 ? path.slice(0, -1) : path; return normalizedAllowed === targetPath || path === to.path; }); if (!isAllowed) { console.warn(`Access denied to ${to.path}. User allowed pages:`, allowedPages); // Redirect to first allowed page if available, else stay/error if (allowedPages.length > 0) { // If dashboard is allowed, go there, else go to the first allowed one const dashboardPath = allowedPages.find(p => p === '/' || p === '/dashboard'); return navigateTo(dashboardPath || allowedPages[0]); } else { // No access to any page - technically this shouldn't happen if user has roles console.error('User has roles but no allowed pages found in configuration.'); // For now, allow root as fallback since index.vue is kept if (to.path === '/') return; } } } catch (error) { console.error('Error checking page access:', error); // On error, we might want to allow or block. Let's allow but log. return; } });