You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.4 KiB
57 lines
1.4 KiB
import { NextRequest, NextResponse } from "next/server";
|
|
import {
|
|
LEGACY_NEWAPIWG_API_KEY_HEADER,
|
|
NEWAPIWG_API_KEY_HEADER,
|
|
} from "@/utils/gatewayHeaders";
|
|
|
|
const AUTH_EXEMPT_API_PREFIXES = [
|
|
"/api/env-status",
|
|
"/api/images/",
|
|
"/api/proxy-media",
|
|
"/api/auth/",
|
|
"/api/captcha/",
|
|
];
|
|
|
|
function hasLoginToken(request: NextRequest): boolean {
|
|
const gatewayApiKey =
|
|
request.headers.get(NEWAPIWG_API_KEY_HEADER)?.trim() ||
|
|
request.headers.get(LEGACY_NEWAPIWG_API_KEY_HEADER)?.trim();
|
|
if (gatewayApiKey) return true;
|
|
|
|
const token = request.headers.get("token")?.trim();
|
|
if (token) return true;
|
|
|
|
const userToken = request.headers.get("X-User-Token")?.trim();
|
|
if (userToken) return true;
|
|
|
|
const authorization = request.headers.get("authorization");
|
|
return /^Bearer\s+.+$/i.test(authorization || "");
|
|
}
|
|
|
|
export function proxy(request: NextRequest) {
|
|
if (request.method === "OPTIONS") {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
const pathname = request.nextUrl.pathname;
|
|
if (AUTH_EXEMPT_API_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
if (!hasLoginToken(request)) {
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
code: "AUTH_REQUIRED",
|
|
error: "请先登录",
|
|
},
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: "/api/:path*",
|
|
};
|
|
|