2023-03-26 06:53:40 +00:00
|
|
|
import { NextRequest, NextResponse } from "next/server";
|
2023-04-10 17:21:34 +00:00
|
|
|
import { getServerSideConfig } from "./app/config/server";
|
2023-03-26 06:53:40 +00:00
|
|
|
import md5 from "spark-md5";
|
|
|
|
|
|
|
|
export const config = {
|
2023-03-29 18:09:15 +00:00
|
|
|
matcher: ["/api/openai", "/api/chat-stream"],
|
2023-03-26 06:53:40 +00:00
|
|
|
};
|
|
|
|
|
2023-04-10 17:21:34 +00:00
|
|
|
const serverConfig = getServerSideConfig();
|
|
|
|
|
2023-04-16 09:20:33 +00:00
|
|
|
function getIP(req: NextRequest) {
|
|
|
|
let ip = req.ip ?? req.headers.get("x-real-ip");
|
|
|
|
const forwardedFor = req.headers.get("x-forwarded-for");
|
|
|
|
|
|
|
|
if (!ip && forwardedFor) {
|
|
|
|
ip = forwardedFor.split(",").at(0) ?? "";
|
|
|
|
}
|
|
|
|
|
|
|
|
return ip;
|
|
|
|
}
|
|
|
|
|
2023-03-29 17:45:26 +00:00
|
|
|
export function middleware(req: NextRequest) {
|
2023-03-26 06:53:40 +00:00
|
|
|
const accessCode = req.headers.get("access-code");
|
2023-03-26 11:58:25 +00:00
|
|
|
const token = req.headers.get("token");
|
2023-03-26 06:53:40 +00:00
|
|
|
const hashedCode = md5.hash(accessCode ?? "").trim();
|
|
|
|
|
2023-04-10 17:21:34 +00:00
|
|
|
console.log("[Auth] allowed hashed codes: ", [...serverConfig.codes]);
|
2023-03-26 06:53:40 +00:00
|
|
|
console.log("[Auth] got access code:", accessCode);
|
|
|
|
console.log("[Auth] hashed access code:", hashedCode);
|
2023-04-16 09:20:33 +00:00
|
|
|
console.log("[User IP] ", getIP(req));
|
|
|
|
console.log("[Time] ", new Date().toLocaleString());
|
2023-03-26 06:53:40 +00:00
|
|
|
|
2023-04-10 17:21:34 +00:00
|
|
|
if (serverConfig.needCode && !serverConfig.codes.has(hashedCode) && !token) {
|
2023-03-26 06:53:40 +00:00
|
|
|
return NextResponse.json(
|
|
|
|
{
|
2023-03-29 17:45:26 +00:00
|
|
|
error: true,
|
2023-03-26 06:53:40 +00:00
|
|
|
needAccessCode: true,
|
2023-03-29 17:45:26 +00:00
|
|
|
msg: "Please go settings page and fill your access code.",
|
2023-03-26 06:53:40 +00:00
|
|
|
},
|
|
|
|
{
|
|
|
|
status: 401,
|
2023-03-29 17:45:26 +00:00
|
|
|
},
|
2023-03-26 06:53:40 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-03-29 17:45:26 +00:00
|
|
|
// inject api key
|
|
|
|
if (!token) {
|
2023-04-10 18:54:31 +00:00
|
|
|
const apiKey = serverConfig.apiKey;
|
2023-03-29 17:45:26 +00:00
|
|
|
if (apiKey) {
|
2023-03-29 18:09:15 +00:00
|
|
|
console.log("[Auth] set system token");
|
2023-03-29 17:45:26 +00:00
|
|
|
req.headers.set("token", apiKey);
|
|
|
|
} else {
|
|
|
|
return NextResponse.json(
|
|
|
|
{
|
|
|
|
error: true,
|
|
|
|
msg: "Empty Api Key",
|
|
|
|
},
|
|
|
|
{
|
|
|
|
status: 401,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
2023-03-29 18:09:15 +00:00
|
|
|
} else {
|
|
|
|
console.log("[Auth] set user token");
|
2023-03-29 17:45:26 +00:00
|
|
|
}
|
|
|
|
|
2023-03-29 17:53:36 +00:00
|
|
|
return NextResponse.next({
|
|
|
|
request: {
|
|
|
|
headers: req.headers,
|
|
|
|
},
|
|
|
|
});
|
2023-03-26 06:53:40 +00:00
|
|
|
}
|