Skip to content

Commit

Permalink
Merge pull request #106 from m00nfly/main
Browse files Browse the repository at this point in the history
Add access authentication by api_key
  • Loading branch information
PawanOsman authored Apr 22, 2024
2 parents 21dc6ef + 4729671 commit d9a36a8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
SERVER_PORT=3040
USER_AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
NEW_SESSION_RETRIES=5
API_KEY=
CLOUDFLARED=true

PROXY=false
Expand Down
28 changes: 28 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ const newSessionRetries: number =
const userAgent =
process.env.USER_AGENT ||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36";
const authKey: string =
process.env.API_KEY || null; // Authorized client apiKey

let cloudflared: ChildProcessWithoutNullStreams;

Expand Down Expand Up @@ -198,6 +200,32 @@ function enableCORS(req: Request, res: Response, next: NextFunction) {

// Middleware to handle chat completions
async function handleChatCompletion(req: Request, res: Response) {
// If .env sets API_KEY and is not empty, the apiKey of req.headers will be verified.
if (authKey) {
const clientApiKey = req.headers.authorization?.split(' ')[1] ?? "null";
if (!clientApiKey || clientApiKey != authKey) {
console.log(
"Request:",
`${req.method} ${req.originalUrl}`,
`${req.body?.messages?.length ?? 0} messages`,
`ClientKey: ${clientApiKey} Verify Failed!`
);

res.write(
JSON.stringify({
status: false,
error: {
message: `Incorrect API key provided: ${clientApiKey}, Authorized access only!`,
type: "invalid_request_error",
code: "invalid_api_key"
},
support: "https://discord.pawan.krd",
})
);
return res.end();
}
}

console.log(
"Request:",
`${req.method} ${req.originalUrl}`,
Expand Down

0 comments on commit d9a36a8

Please sign in to comment.