Spaces:
Running
Running
File size: 1,619 Bytes
fecff63 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
// Paths that don't require authentication
const PUBLIC_PATHS = ["/login", "/signup", "/api/auth"];
function isPublicPath(pathname: string): boolean {
return PUBLIC_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"));
}
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Allow public paths (login, auth callbacks)
if (isPublicPath(pathname)) {
return NextResponse.next();
}
// Production-only blocking without explicit config
if (process.env.NODE_ENV === "production") {
const explicitlyEnabled = process.env.ADMIN_ALLOW_PRODUCTION === "true";
const hasAuth = Boolean(
process.env.BETTER_AUTH_SECRET && process.env.BETTER_AUTH_URL,
);
if (!explicitlyEnabled || !hasAuth) {
return new NextResponse(
"MicProtocol Admin is not exposed in production without explicit configuration. " +
"Set ADMIN_ALLOW_PRODUCTION=true and configure real authentication to enable it.",
{ status: 503 },
);
}
}
// Auth gating: check for Better Auth session cookie or dev-mode header
const sessionCookie = request.cookies.get("better-auth.session");
const devUserId = request.headers.get("x-user-id");
if (!sessionCookie && !devUserId) {
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("callbackUrl", pathname);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next|.*\\..*).*)"],
};
|