middleware.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. if (apiKey) {
  30. req.headers.set("token", apiKey);
  31. } else {
  32. return NextResponse.json(
  33. {
  34. error: true,
  35. msg: "Empty Api Key",
  36. },
  37. {
  38. status: 401,
  39. },
  40. );
  41. }
  42. }
  43. return NextResponse.next();
  44. }