auth.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. const serverConfig = getServerSideConfig();
  6. function getIP(req: NextRequest) {
  7. let ip = req.ip ?? req.headers.get("x-real-ip");
  8. const forwardedFor = req.headers.get("x-forwarded-for");
  9. if (!ip && forwardedFor) {
  10. ip = forwardedFor.split(",").at(0) ?? "";
  11. }
  12. return ip;
  13. }
  14. function parseApiKey(bearToken: string) {
  15. const token = bearToken.trim().replaceAll("Bearer ", "").trim();
  16. const isOpenAiKey = !token.startsWith(ACCESS_CODE_PREFIX);
  17. return {
  18. accessCode: isOpenAiKey ? "" : token.slice(ACCESS_CODE_PREFIX.length),
  19. apiKey: isOpenAiKey ? token : "",
  20. };
  21. }
  22. export function auth(req: NextRequest) {
  23. const authToken = req.headers.get("Authorization") ?? "";
  24. // check if it is openai api key or user token
  25. const { accessCode, apiKey: token } = parseApiKey(authToken);
  26. const hashedCode = md5.hash(accessCode ?? "").trim();
  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) && !token) {
  33. return {
  34. error: true,
  35. needAccessCode: true,
  36. msg: "Please go settings page and fill your access code.",
  37. };
  38. }
  39. // if user does not provide an api key, inject system api key
  40. if (!token) {
  41. const apiKey = serverConfig.apiKey;
  42. if (apiKey) {
  43. console.log("[Auth] use system api key");
  44. req.headers.set("Authorization", `Bearer ${apiKey}`);
  45. } else {
  46. console.log("[Auth] admin did not provide an api key");
  47. return {
  48. error: true,
  49. msg: "Empty Api Key",
  50. };
  51. }
  52. } else {
  53. console.log("[Auth] use user api key");
  54. }
  55. return {
  56. error: false,
  57. };
  58. }