initial version of the app
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { decrypt } from '@/lib/session';
|
||||
|
||||
// Protected routes that require authentication
|
||||
const protectedRoutes = ['/dashboard', '/admin', '/bookings', '/profile'];
|
||||
// Admin routes that require admin role
|
||||
const adminRoutes = ['/admin'];
|
||||
// Auth routes that should redirect if already authenticated
|
||||
const authRoutes = ['/login', '/register'];
|
||||
|
||||
export default async function middleware(req: NextRequest) {
|
||||
const path = req.nextUrl.pathname;
|
||||
const isProtectedRoute = protectedRoutes.some((route) => path.startsWith(route));
|
||||
const isAdminRoute = adminRoutes.some((route) => path.startsWith(route));
|
||||
const isAuthRoute = authRoutes.includes(path);
|
||||
|
||||
const cookie = req.cookies.get('session')?.value;
|
||||
const session = await decrypt(cookie);
|
||||
|
||||
// Redirect to login if accessing protected route without session
|
||||
if (isProtectedRoute && !session?.userId) {
|
||||
return NextResponse.redirect(new URL('/login', req.nextUrl));
|
||||
}
|
||||
|
||||
// Redirect to dashboard if accessing auth routes while authenticated
|
||||
if (isAuthRoute && session?.userId) {
|
||||
return NextResponse.redirect(new URL('/dashboard', req.nextUrl));
|
||||
}
|
||||
|
||||
// Redirect to dashboard if accessing admin route without admin role
|
||||
if (isAdminRoute && session?.role !== 'admin') {
|
||||
return NextResponse.redirect(new URL('/dashboard', req.nextUrl));
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
|
||||
};
|
||||
Reference in New Issue
Block a user