auth.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { NextRequest } from "next/server";
  2. import { getServerSideConfig } from "../config/server";
  3. import md5 from "spark-md5";
  4. import { ACCESS_CODE_PREFIX } from "../constant";
  5. function getIP(req: NextRequest) {
  6. let ip = req.ip ?? req.headers.get("x-real-ip");
  7. const forwardedFor = req.headers.get("x-forwarded-for");
  8. if (!ip && forwardedFor) {
  9. ip = forwardedFor.split(",").at(0) ?? "";
  10. }
  11. return ip;
  12. }
  13. function parseApiKey(bearToken: string) {
  14. const token = bearToken.trim().replaceAll("Bearer ", "").trim();
  15. const isOpenAiKey = !token.startsWith(ACCESS_CODE_PREFIX);
  16. return {
  17. accessCode: isOpenAiKey ? "" : token.slice(ACCESS_CODE_PREFIX.length),
  18. apiKey: isOpenAiKey ? token : "",
  19. };
  20. }
  21. export function auth(req: NextRequest) {
  22. const authToken = req.headers.get("Authorization") ?? "";
  23. // check if it is openai api key or user token
  24. const { accessCode, apiKey } = parseApiKey(authToken);
  25. const hashedCode = md5.hash(accessCode ?? "").trim();
  26. const serverConfig = getServerSideConfig();
  27. if (serverConfig.OAUTH_AUTHORIZE_ENDPOINT && serverConfig.OAUTH_CLIENT_ID) {
  28. return {
  29. error: false,
  30. };
  31. }
  32. console.log("[Auth] allowed hashed codes: ", [...serverConfig.codes]);
  33. console.log("[Auth] got access code:", accessCode);
  34. console.log("[Auth] hashed access code:", hashedCode);
  35. console.log("[User IP] ", getIP(req));
  36. console.log("[Time] ", new Date().toLocaleString());
  37. if (serverConfig.needCode && !serverConfig.codes.has(hashedCode) && !apiKey) {
  38. return {
  39. error: true,
  40. msg: !accessCode ? "empty access code" : "wrong access code",
  41. };
  42. }
  43. if (serverConfig.hideUserApiKey && !!apiKey) {
  44. return {
  45. error: true,
  46. msg: "you are not allowed to access openai with your own api key",
  47. };
  48. }
  49. // if user does not provide an api key, inject system api key
  50. if (!apiKey) {
  51. const serverApiKey = serverConfig.isAzure
  52. ? serverConfig.azureApiKey
  53. : serverConfig.apiKey;
  54. if (serverApiKey) {
  55. console.log("[Auth] use system api key");
  56. req.headers.set(
  57. "Authorization",
  58. `${serverConfig.isAzure ? "" : "Bearer "}${serverApiKey}`,
  59. );
  60. } else {
  61. console.log("[Auth] admin did not provide an api key");
  62. }
  63. } else {
  64. console.log("[Auth] use user api key");
  65. }
  66. return {
  67. error: false,
  68. };
  69. }