middleware.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { NextRequest, NextResponse } from "next/server";
  2. import { ACCESS_CODES } from "./app/api/access";
  3. import md5 from "spark-md5";
  4. export const config = {
  5. matcher: ["/api/chat", "/api/chat-stream"],
  6. };
  7. export function middleware(req: NextRequest) {
  8. const accessCode = req.headers.get("access-code");
  9. const token = req.headers.get("token");
  10. const hashedCode = md5.hash(accessCode ?? "").trim();
  11. console.log("[Auth] allowed hashed codes: ", [...ACCESS_CODES]);
  12. console.log("[Auth] got access code:", accessCode);
  13. console.log("[Auth] hashed access code:", hashedCode);
  14. if (ACCESS_CODES.size > 0 && !ACCESS_CODES.has(hashedCode) && !token) {
  15. return NextResponse.json(
  16. {
  17. error: true,
  18. needAccessCode: true,
  19. msg: "Please go settings page and fill your access code.",
  20. },
  21. {
  22. status: 401,
  23. },
  24. );
  25. }
  26. // inject api key
  27. if (!token) {
  28. const apiKey = process.env.OPENAI_API_KEY;
  29. console.log("apiKey", apiKey);
  30. if (apiKey) {
  31. req.headers.set("token", apiKey);
  32. } else {
  33. return NextResponse.json(
  34. {
  35. error: true,
  36. msg: "Empty Api Key",
  37. },
  38. {
  39. status: 401,
  40. },
  41. );
  42. }
  43. }
  44. return NextResponse.next({
  45. request: {
  46. headers: req.headers,
  47. },
  48. });
  49. }