Files
tt-booking/middleware.ts
T
2025-10-08 22:37:14 +01:00

52 lines
1.8 KiB
TypeScript

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;
// Debug logging for production
if (!cookie && (isProtectedRoute || isAuthRoute)) {
console.log(`No session cookie found for ${path}, headers:`, {
host: req.headers.get('host'),
'x-forwarded-proto': req.headers.get('x-forwarded-proto'),
'x-forwarded-host': req.headers.get('x-forwarded-host'),
cookies: req.headers.get('cookie')
});
}
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$).*)'],
};