2023-03-26 14:53:40 +08:00
|
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
|
|
import { ACCESS_CODES } from "./app/api/access";
|
|
|
|
import md5 from "spark-md5";
|
|
|
|
|
|
|
|
export const config = {
|
|
|
|
matcher: ["/api/chat", "/api/chat-stream"],
|
|
|
|
};
|
|
|
|
|
|
|
|
export function middleware(req: NextRequest, res: NextResponse) {
|
|
|
|
const accessCode = req.headers.get("access-code");
|
2023-03-26 19:58:25 +08:00
|
|
|
const token = req.headers.get("token");
|
2023-03-26 14:53:40 +08:00
|
|
|
const hashedCode = md5.hash(accessCode ?? "").trim();
|
|
|
|
|
|
|
|
console.log("[Auth] allowed hashed codes: ", [...ACCESS_CODES]);
|
|
|
|
console.log("[Auth] got access code:", accessCode);
|
|
|
|
console.log("[Auth] hashed access code:", hashedCode);
|
|
|
|
|
2023-03-26 19:58:25 +08:00
|
|
|
if (ACCESS_CODES.size > 0 && !ACCESS_CODES.has(hashedCode) && !token) {
|
2023-03-26 14:53:40 +08:00
|
|
|
return NextResponse.json(
|
|
|
|
{
|
|
|
|
needAccessCode: true,
|
|
|
|
hint: "Please go settings page and fill your access code.",
|
|
|
|
},
|
|
|
|
{
|
|
|
|
status: 401,
|
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return NextResponse.next();
|
|
|
|
}
|