64 lines
1.7 KiB
TypeScript
64 lines
1.7 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import type { NextRequest } from 'next/server';
|
|
|
|
// Routes that require authentication
|
|
const protectedRoutes = [
|
|
'/visualisasi',
|
|
'/keloladata',
|
|
];
|
|
|
|
// Routes that are always accessible
|
|
const publicRoutes = [
|
|
'/',
|
|
'/api/auth/login',
|
|
];
|
|
|
|
export function middleware(request: NextRequest) {
|
|
const { pathname } = request.nextUrl;
|
|
|
|
// Check if the route is public
|
|
if (publicRoutes.some(route => pathname.startsWith(route))) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
// Check if the route requires authentication
|
|
if (protectedRoutes.some(route => pathname.startsWith(route))) {
|
|
// Get user session from cookies
|
|
const userSession = request.cookies.get('user_session');
|
|
|
|
if (!userSession) {
|
|
// Redirect to home page if not authenticated
|
|
return NextResponse.redirect(new URL('/', request.url));
|
|
}
|
|
|
|
try {
|
|
const userData = JSON.parse(userSession.value);
|
|
|
|
// Check if user has access to keloladata routes (admin only)
|
|
if (pathname.startsWith('/keloladata') && userData.role_user !== 'admin') {
|
|
// Redirect to home page if not admin
|
|
return NextResponse.redirect(new URL('/', request.url));
|
|
}
|
|
|
|
return NextResponse.next();
|
|
} catch (error) {
|
|
// Invalid session, redirect to home
|
|
return NextResponse.redirect(new URL('/', request.url));
|
|
}
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: [
|
|
/*
|
|
* Match all request paths except for the ones starting with:
|
|
* - api (API routes)
|
|
* - _next/static (static files)
|
|
* - _next/image (image optimization files)
|
|
* - favicon.ico (favicon file)
|
|
*/
|
|
'/((?!api|_next/static|_next/image|favicon.ico).*)',
|
|
],
|
|
};
|