auth.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. console.log("[Auth] allowed hashed codes: ", [...serverConfig.codes]);
  28. console.log("[Auth] got access code:", accessCode);
  29. console.log("[Auth] hashed access code:", hashedCode);
  30. console.log("[User IP] ", getIP(req));
  31. console.log("[Time] ", new Date().toLocaleString());
  32. if (serverConfig.needCode && !serverConfig.codes.has(hashedCode) && !apiKey) {
  33. return {
  34. error: true,
  35. msg: !accessCode ? "empty access code" : "wrong access code",
  36. };
  37. }
  38. if (serverConfig.hideUserApiKey && !!apiKey) {
  39. return {
  40. error: true,
  41. msg: "you are not allowed to access openai with your own api key",
  42. };
  43. }
  44. // if user does not provide an api key, inject system api key
  45. if (!apiKey) {
  46. const serverApiKey = serverConfig.isAzure
  47. ? serverConfig.azureApiKey
  48. : serverConfig.apiKey;
  49. if (serverApiKey) {
  50. console.log("[Auth] use system api key");
  51. req.headers.set(
  52. "Authorization",
  53. `${serverConfig.isAzure ? "" : "Bearer "}${serverApiKey}`,
  54. );
  55. } else {
  56. console.log("[Auth] admin did not provide an api key");
  57. }
  58. } else {
  59. console.log("[Auth] use user api key");
  60. }
  61. return {
  62. error: false,
  63. };
  64. }