import type { NextRequest } from "next/server"; import { getToken } from "next-auth/jwt"; import { NextResponse } from "next/server"; export async function middleware(request: NextRequest) { const path = request.nextUrl.pathname; const cookies = request.cookies; const myCookie: any = cookies.get("emailForForgetPassword"); const isPasswordResetting = myCookie?.value?.length > 0; // console.log(isPasswordResetting, "myCookiemyCookie"); // Define public paths const git = ""; const isPublicPath = [ "/", "/login", "/signup", "/forgot-password", "/admin/login", "/dashboard/copy-to-clipboard", ...(isPasswordResetting ? ["/otp"] : []), ...(isPasswordResetting ? ["/reset-password"] : []), ].includes(path); const userData: any = await getToken({ req: request }); const { isVerified, verificationToken: token, userType, tier, name: userName, } = userData?.user || {}; if (process.env.NODE_ENV === "development") { console.log("Requested Path:", path); } if (!isPublicPath) { if (!token) { console.log("Redirecting to /login due to missing token"); return NextResponse.redirect(new URL("/login", request.url)); } // if ((tier === null || tier === undefined) && isVerified && token && !path.includes("/admin") && path !== "/") { // console.log("Redirecting to / because tier is null"); // return NextResponse.redirect(new URL("/", request.url)); // } if ( !userName && isVerified && userType === "user" && path !== "/create-profile" ) { return NextResponse.redirect(new URL("/create-profile", request.url)); } if (!isVerified && userType === "user" && path !== "/otp") { return NextResponse.redirect(new URL("/otp", request.url)); } if ((token && isVerified && path == "/otp") || path == "/reset-password") { if (userType === "admin" && token) { return NextResponse.redirect(new URL("/admin/product", request.url)); } else if (userType === "user" && token) { return NextResponse.redirect(new URL("/dashboard", request.url)); } } if ( token && isVerified && userType === "user" && userName && path.startsWith("/admin") ) { return NextResponse.redirect(new URL("/dashboard", request.url)); } } if (isPublicPath) { if (userType === "user" && !isVerified && token) { console.log("Redirecting to /otp due to unverified token"); return NextResponse.redirect(new URL("/otp", request.url)); } // if ((tier === null || tier === undefined) && isVerified && token && path !== "/") { // console.log("Redirecting to / because tier is null"); // return NextResponse.redirect(new URL("/", request.url)); // } if (userType === "admin" && token) { return NextResponse.redirect(new URL("/admin/product", request.url)); } } if (isPublicPath && isVerified && token && userType === "user" && tier !== null && tier !== undefined) { if (!userName) { return NextResponse.redirect(new URL("/create-profile", request.url)); } else { return NextResponse.redirect(new URL("/dashboard", request.url)); } } return NextResponse.next(); } export const config = { matcher: ["/((?!api|_next|.*\\..*).*)"], };