2025-12-22 10:29:33 +05:30
|
|
|
import { auth } from "@/auth";
|
|
|
|
|
import { NextResponse } from "next/server";
|
|
|
|
|
|
|
|
|
|
// Public routes that don't require authentication
|
2026-01-19 09:46:32 +05:30
|
|
|
const publicRoutes = ["/login", "/signup", "/forgot-password", "/reset-password", "/verify-email", "/contact"];
|
2025-12-22 10:29:33 +05:30
|
|
|
|
|
|
|
|
export default auth((req) => {
|
|
|
|
|
const { nextUrl } = req;
|
|
|
|
|
const isLoggedIn = !!req.auth;
|
2026-01-11 21:30:57 +05:30
|
|
|
const userRole = (req.auth?.user as any)?.role;
|
2025-12-22 10:29:33 +05:30
|
|
|
|
|
|
|
|
const isPublicRoute = publicRoutes.some(
|
|
|
|
|
(route) => nextUrl.pathname === route || nextUrl.pathname.startsWith(route + "/")
|
|
|
|
|
);
|
|
|
|
|
|
2026-01-11 21:30:57 +05:30
|
|
|
const isAgentRoute = nextUrl.pathname.startsWith("/agent");
|
|
|
|
|
const isUserRoute = nextUrl.pathname.startsWith("/user");
|
|
|
|
|
|
2025-12-22 10:29:33 +05:30
|
|
|
const isApiRoute = nextUrl.pathname.startsWith("/api");
|
|
|
|
|
const isStaticRoute = nextUrl.pathname.startsWith("/_next") ||
|
|
|
|
|
nextUrl.pathname.startsWith("/assets") ||
|
|
|
|
|
nextUrl.pathname.includes(".");
|
|
|
|
|
|
|
|
|
|
// Skip middleware for API routes and static files
|
|
|
|
|
if (isApiRoute || isStaticRoute) {
|
|
|
|
|
return NextResponse.next();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Redirect logged-in users away from public routes (login, signup)
|
|
|
|
|
if (isLoggedIn && isPublicRoute) {
|
2026-01-11 22:09:41 +05:30
|
|
|
// Redirect to home page instead of dashboard
|
|
|
|
|
return NextResponse.redirect(new URL("/", nextUrl.origin));
|
2025-12-22 10:29:33 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Redirect non-logged-in users to login page for protected routes
|
|
|
|
|
if (!isLoggedIn && !isPublicRoute) {
|
|
|
|
|
const loginUrl = new URL("/login", nextUrl.origin);
|
|
|
|
|
loginUrl.searchParams.set("callbackUrl", nextUrl.pathname);
|
|
|
|
|
return NextResponse.redirect(loginUrl);
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-11 21:30:57 +05:30
|
|
|
// Role-based route protection
|
|
|
|
|
if (isLoggedIn) {
|
|
|
|
|
// Prevent regular users from accessing agent routes
|
|
|
|
|
if (isAgentRoute && userRole !== "AGENT") {
|
2026-01-20 01:24:43 +05:30
|
|
|
return NextResponse.redirect(new URL("/user/dashboard", nextUrl.origin));
|
2026-01-11 21:30:57 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Prevent agents from accessing user routes
|
|
|
|
|
if (isUserRoute && userRole === "AGENT") {
|
|
|
|
|
return NextResponse.redirect(new URL("/agent/dashboard", nextUrl.origin));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-22 10:29:33 +05:30
|
|
|
return NextResponse.next();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
export const config = {
|
|
|
|
|
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
|
|
|
|
|
};
|