Files
antrean-operasi/middleware/checkPageAccess.ts
2026-02-18 08:21:58 +07:00

42 lines
1.5 KiB
TypeScript

// 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 auth pages, error pages
const publicPaths = ['/auth/login', '/auth/register', '/'];
if (publicPaths.includes(to.path)) {
return;
}
const { user } = useUserInfo();
// If not authenticated, let auth middleware handle it
if (!user.value) {
return;
}
const { getAllowedPages } = useHakAkses();
try {
const allowedPages = await getAllowedPages();
// Check if user has access to this page
if (!allowedPages.includes(to.path)) {
console.warn(`Access denied to ${to.path}. User allowed pages:`, allowedPages);
// Redirect to dashboard or first allowed page
if (allowedPages.length > 0) {
const firstPage = allowedPages.includes('/dashboard') ? '/dashboard' : allowedPages[0];
return navigateTo(firstPage);
} else {
// No access to any page - redirect to login with error
return navigateTo('/auth/login?error=' + encodeURIComponent('You do not have access to any pages. Please contact administrator.'));
}
}
} catch (error) {
console.error('Error checking page access:', error);
// Allow access on error to prevent blocking user
return;
}
});