Spaces:
Sleeping
Sleeping
File size: 2,209 Bytes
4c2a557 a572854 4c2a557 a572854 4c2a557 a572854 4c2a557 a572854 4c2a557 | 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const API_KEY = process.env.API_KEY;
const ACCESS_TOKEN = process.env.ACCESS_TOKEN;
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (
pathname.startsWith("/api/v1/inlet") ||
pathname.startsWith("/api/v1/outlet") ||
pathname.startsWith("/api/v1/models") ||
pathname.startsWith("/api/v1/panel") ||
pathname.startsWith("/api/v1/config") ||
pathname.startsWith("/api/v1/users")
) {
const token =
pathname.startsWith("/api/v1/panel") ||
pathname.startsWith("/api/v1/config") ||
pathname.startsWith("/api/v1/users") ||
pathname.startsWith("/api/v1/models")
? ACCESS_TOKEN
: API_KEY;
if (!token) {
console.error("API Key or Access Token is not set");
return NextResponse.json(
{ error: "Server configuration error" },
{ status: 500 }
);
}
const authHeader = request.headers.get("authorization");
const providedKey = authHeader?.replace("Bearer ", "");
if (!providedKey || providedKey !== token) {
console.log("Invalid API key or token");
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
return NextResponse.next();
} else if (!pathname.startsWith("/api/")) {
if (!ACCESS_TOKEN) {
console.error("ACCESS_TOKEN is not set");
return NextResponse.json(
{ error: "Server configuration error" },
{ status: 500 }
);
}
if (pathname === "/token") {
return NextResponse.next();
}
const response = NextResponse.next();
response.headers.set(
"Cache-Control",
"no-store, no-cache, must-revalidate, proxy-revalidate"
);
response.headers.set("Pragma", "no-cache");
response.headers.set("Expires", "0");
return response;
} else if (pathname.startsWith("/api/config/key")) {
return NextResponse.next();
} else if (pathname.startsWith("/api/init")) {
return NextResponse.next();
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
|