27 lines
863 B
TypeScript
27 lines
863 B
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|||
|
|
import { SESSION_COOKIE_NAME, verifySessionToken } from "@/lib/auth/session";
|
||
|
|
|
||
|
|
export default async function proxy(req: NextRequest) {
|
||
|
|
const { pathname } = req.nextUrl;
|
||
|
|
const isAuthenticated = await verifySessionToken(req.cookies.get(SESSION_COOKIE_NAME)?.value);
|
||
|
|
|
||
|
|
if (isAuthenticated) {
|
||
|
|
if (pathname === "/login") {
|
||
|
|
return NextResponse.redirect(new URL("/", req.url));
|
||
|
|
}
|
||
|
|
return NextResponse.next();
|
||
|
|
}
|
||
|
|
|
||
|
|
if (pathname.startsWith("/api/")) {
|
||
|
|
return NextResponse.json({ error: "unauthorized" }, { status: 401 });
|
||
|
|
}
|
||
|
|
|
||
|
|
const loginUrl = new URL("/login", req.url);
|
||
|
|
loginUrl.searchParams.set("from", pathname);
|
||
|
|
return NextResponse.redirect(loginUrl);
|
||
|
|
}
|
||
|
|
|
||
|
|
export const config = {
|
||
|
|
matcher: ["/((?!_next/static|_next/image|favicon.ico|login|api/auth/login|api/health).*)"],
|
||
|
|
};
|