67 lines
1.7 KiB
TypeScript
67 lines
1.7 KiB
TypeScript
import createMiddleware from "next-intl/middleware";
|
|
import { NextResponse } from "next/server";
|
|
import type { NextRequest } from "next/server";
|
|
|
|
import { routing } from "./i18n/routing";
|
|
|
|
const intlMiddleware = createMiddleware(routing);
|
|
|
|
function isRootBasicAuthConfigured(): boolean {
|
|
return Boolean(process.env.ROOT_BASIC_AUTH_USER && process.env.ROOT_BASIC_AUTH_PASS);
|
|
}
|
|
|
|
function isRootBasicAuthValid(request: NextRequest): boolean {
|
|
if (!isRootBasicAuthConfigured()) {
|
|
return false;
|
|
}
|
|
|
|
const header = request.headers.get("authorization");
|
|
if (!header || !header.startsWith("Basic ")) {
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
const decoded = atob(header.slice(6));
|
|
const index = decoded.indexOf(":");
|
|
if (index === -1) {
|
|
return false;
|
|
}
|
|
|
|
const user = decoded.slice(0, index);
|
|
const pass = decoded.slice(index + 1);
|
|
|
|
return (
|
|
user === process.env.ROOT_BASIC_AUTH_USER &&
|
|
pass === process.env.ROOT_BASIC_AUTH_PASS
|
|
);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export default async function middleware(request: NextRequest) {
|
|
const { pathname } = request.nextUrl;
|
|
const isRootBaseRoute = pathname === "/root" || pathname.startsWith("/root/");
|
|
|
|
const isRootRoute = isRootBaseRoute;
|
|
|
|
if (isRootRoute && isRootBasicAuthConfigured() && !isRootBasicAuthValid(request)) {
|
|
return new NextResponse("Authentication required", {
|
|
status: 401,
|
|
headers: {
|
|
"WWW-Authenticate": 'Basic realm="Root Area", charset="UTF-8"',
|
|
},
|
|
});
|
|
}
|
|
|
|
if (isRootBaseRoute) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
return intlMiddleware(request);
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ["/((?!api|trpc|_next|_vercel|.*\\..*).*)"],
|
|
};
|