Files
clienthub/src/proxy.ts
T
Simone Cavalli 69f8a7eae3 feat(02-01): extend proxy.ts with admin session guard, add login page
- Extend src/proxy.ts to guard /admin/* routes with getToken() JWT check
- /admin/login and /api/auth/* exempted from session guard (pass-through)
- Unauthenticated /admin/* requests redirect to /admin/login?callbackUrl=...
- /c/:path* client token validation logic preserved unchanged
- matcher updated: ["/admin/:path*", "/c/:path*"]
- Create src/app/admin/login/page.tsx: email+password form, signIn('credentials'), error on failure, redirect on success
- Fix: Next.js 16 requires export named 'proxy' not 'middleware'
- Fix: useSearchParams wrapped in Suspense boundary (Next.js App Router requirement)
2026-05-15 10:42:21 +02:00

65 lines
2.1 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
export async function proxy(request: NextRequest) {
const pathname = request.nextUrl.pathname;
// ── ADMIN GUARD ──────────────────────────────────────────────────────────
if (pathname.startsWith("/admin")) {
// Allow the login page and NextAuth API routes through without session check
if (
pathname === "/admin/login" ||
pathname.startsWith("/api/auth")
) {
return NextResponse.next();
}
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
});
if (!token) {
const loginUrl = new URL("/admin/login", request.url);
loginUrl.searchParams.set("callbackUrl", pathname);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
}
// ── CLIENT TOKEN GUARD ───────────────────────────────────────────────────
if (pathname.startsWith("/c/")) {
const tokenMatch = pathname.match(/^\/c\/([a-zA-Z0-9_-]+)/);
if (!tokenMatch) {
return NextResponse.rewrite(new URL("/not-found", request.url));
}
const clientToken = tokenMatch[1];
try {
// Call internal Node.js API route — Edge middleware cannot use postgres-js directly
// postgres-js requires Node.js net/tls which are unavailable in the Edge runtime
const validateUrl = new URL(
`/api/internal/validate-token?token=${encodeURIComponent(clientToken)}`,
request.url
);
const res = await fetch(validateUrl.toString());
if (!res.ok) {
return NextResponse.rewrite(new URL("/not-found", request.url));
}
return NextResponse.next();
} catch {
return NextResponse.rewrite(new URL("/not-found", request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/admin/:path*", "/c/:path*"],
};