ChatGPT-Next-Web/app/api/auth.ts

79 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-05-03 15:08:37 +00:00
import { NextRequest } from "next/server";
import { getServerSideConfig } from "../config/server";
import md5 from "spark-md5";
import { ACCESS_CODE_PREFIX } from "../constant";
2023-05-03 15:08:37 +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;
}
function parseApiKey(bearToken: string) {
const token = bearToken.trim().replaceAll("Bearer ", "").trim();
const isOpenAiKey = !token.startsWith(ACCESS_CODE_PREFIX);
2023-05-03 15:08:37 +00:00
return {
accessCode: isOpenAiKey ? "" : token.slice(ACCESS_CODE_PREFIX.length),
2023-05-03 15:08:37 +00:00
apiKey: isOpenAiKey ? token : "",
};
}
export function auth(req: NextRequest) {
const authToken = req.headers.get("Authorization") ?? "";
// check if it is openai api key or user token
2023-11-09 18:43:30 +00:00
const { accessCode, apiKey } = parseApiKey(authToken);
2023-05-03 15:08:37 +00:00
const hashedCode = md5.hash(accessCode ?? "").trim();
2023-05-17 18:15:30 +00:00
const serverConfig = getServerSideConfig();
2023-05-03 15:08:37 +00:00
console.log("[Auth] allowed hashed codes: ", [...serverConfig.codes]);
console.log("[Auth] got access code:", accessCode);
console.log("[Auth] hashed access code:", hashedCode);
console.log("[User IP] ", getIP(req));
console.log("[Time] ", new Date().toLocaleString());
2023-11-09 18:43:30 +00:00
if (serverConfig.needCode && !serverConfig.codes.has(hashedCode) && !apiKey) {
2023-05-03 15:08:37 +00:00
return {
error: true,
2023-05-15 17:58:58 +00:00
msg: !accessCode ? "empty access code" : "wrong access code",
2023-05-03 15:08:37 +00:00
};
}
if (serverConfig.hideUserApiKey && !!apiKey) {
return {
error: true,
msg: "you are not allowed to access openai with your own api key",
};
}
2023-05-03 15:08:37 +00:00
// if user does not provide an api key, inject system api key
2023-11-09 18:43:30 +00:00
if (!apiKey) {
const serverApiKey = serverConfig.isAzure
? serverConfig.azureApiKey
: serverConfig.apiKey;
if (serverApiKey) {
2023-05-03 15:08:37 +00:00
console.log("[Auth] use system api key");
2023-11-09 18:43:30 +00:00
req.headers.set(
"Authorization",
`${serverConfig.isAzure ? "" : "Bearer "}${serverApiKey}`,
);
2023-05-03 15:08:37 +00:00
} else {
console.log("[Auth] admin did not provide an api key");
}
} else {
console.log("[Auth] use user api key");
}
return {
error: false,
};
}