32 lines
1.0 KiB
TypeScript
32 lines
1.0 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import type { NextRequest } from "next/server";
|
|
import { verifyAndDecode } from "@/lib/auth";
|
|
|
|
const protectedPrefixes = ["/dashboard", "/quiz", "/label", "/admin", "/onboarding", "/codebook"];
|
|
|
|
export function proxy(request: NextRequest) {
|
|
const path = request.nextUrl.pathname;
|
|
const sessionCookie = request.cookies.get("session")?.value;
|
|
|
|
const isValid = sessionCookie ? verifyAndDecode(sessionCookie) !== null : false;
|
|
|
|
// If on login page with valid session, redirect to dashboard
|
|
if (path === "/" && isValid) {
|
|
return NextResponse.redirect(new URL("/dashboard", request.url));
|
|
}
|
|
|
|
// If on protected route without valid session, redirect to login
|
|
const isProtected = protectedPrefixes.some((prefix) =>
|
|
path.startsWith(prefix),
|
|
);
|
|
if (isProtected && !isValid) {
|
|
return NextResponse.redirect(new URL("/", request.url));
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
|
|
};
|