support authentication via APIKEY configuration

This commit is contained in:
jinhui.li
2025-07-17 12:49:14 +08:00
parent f7f6943d31
commit 49502e1534
9 changed files with 69 additions and 4 deletions

33
src/middleware/auth.ts Normal file
View File

@@ -0,0 +1,33 @@
import { FastifyRequest, FastifyReply } from "fastify";
export const apiKeyAuth =
(config: any) =>
(req: FastifyRequest, reply: FastifyReply, done: () => void) => {
if (["/", "/health"].includes(req.url)) {
return done();
}
const apiKey = config.APIKEY;
if (!apiKey) {
return done();
}
const authKey: string =
req.headers.authorization || req.headers["x-api-key"];
if (!authKey) {
reply.status(401).send("APIKEY is missing");
return;
}
let token = "";
if (authKey.startsWith("Bearer")) {
token = authKey.split(" ")[1];
} else {
token = authKey;
}
if (token !== apiKey) {
reply.status(401).send("Invalid API key");
return;
}
done();
};