diff --git a/.env.example b/.env.example index 91930f6..bd196eb 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,6 @@ # Do not share your OpenAI API key with anyone! It should remain a secret. -OPENAI_API_KEY=YOUR_API_KEY +OPENAI_API_KEY=YOUR_OPENAI_API_KEY # Optional. -# OPENAI_API_ENDPOINT=YOUR_API_ENDPOINT +# OPENAI_API_ENDPOINT=YOUR_OPENAI_API_ENDPOINT # USAGE_DATABASE_URL=postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=sqlchat_usage +# API_KEY=YOUR_API_KEY diff --git a/src/components/ConversationView/index.tsx b/src/components/ConversationView/index.tsx index b131c6e..d7ba409 100644 --- a/src/components/ConversationView/index.tsx +++ b/src/components/ConversationView/index.tsx @@ -2,6 +2,7 @@ import axios from "axios"; import { first, head, last } from "lodash-es"; import { useEffect, useRef, useState } from "react"; import { toast } from "react-hot-toast"; +import { API_KEY } from "@/env"; import { getAssistantById, getPromptGeneratorOfAssistant, @@ -171,12 +172,17 @@ const ConversationView = () => { content: prompt, }); + const requestHeaders: any = {}; + if (API_KEY) { + requestHeaders["Authorization"] = `Bearer ${API_KEY}`; + } const rawRes = await fetch("/api/chat", { method: "POST", body: JSON.stringify({ messages: formatedMessageList, openAIApiConfig: settingStore.setting.openAIApiConfig, }), + headers: requestHeaders, }); if (!rawRes.ok) { diff --git a/src/env.ts b/src/env.ts new file mode 100644 index 0000000..db7ba85 --- /dev/null +++ b/src/env.ts @@ -0,0 +1,2 @@ +// API_KEY is using to limit those authorized to use the API and protect the API endpoint. +export const API_KEY = process.env.API_KEY || ""; diff --git a/src/pages/api/chat.ts b/src/pages/api/chat.ts index e7a0ac2..a57ecc2 100644 --- a/src/pages/api/chat.ts +++ b/src/pages/api/chat.ts @@ -1,5 +1,6 @@ import { createParser, ParsedEvent, ReconnectInterval } from "eventsource-parser"; import { NextRequest } from "next/server"; +import { API_KEY } from "@/env"; import { openAIApiEndpoint, openAIApiKey } from "@/utils"; export const config = { @@ -13,6 +14,15 @@ const getApiEndpoint = (apiEndpoint: string) => { }; const handler = async (req: NextRequest) => { + if (API_KEY) { + const auth = req.headers.get("Authorization"); + if (!auth || auth !== `Bearer ${API_KEY}`) { + return new Response("Unauthorized", { + status: 401, + }); + } + } + const reqBody = await req.json(); const openAIApiConfig = reqBody.openAIApiConfig; const apiKey = openAIApiConfig?.key || openAIApiKey;