diff --git a/src/runtime/server/middleware/apiAuth.ts b/src/runtime/server/middleware/apiAuth.ts index d79300c..10ce845 100644 --- a/src/runtime/server/middleware/apiAuth.ts +++ b/src/runtime/server/middleware/apiAuth.ts @@ -1,10 +1,34 @@ -import { defineEventHandler, H3Event } from "h3"; -import apiRequestValidator from "../../../utils/apiRequestValidator"; +import { defineEventHandler, H3Event, createError, eventHandler } from "h3"; // @ts-ignore to avoid type error on useRuntimeConfig, which will be available at runtime in the app // prettier-ignore const { public: { appApiKey }} = useRuntimeConfig(); -export default defineEventHandler((event: H3Event) => { - apiRequestValidator(appApiKey)(event); -}); +export default defineEventHandler( + eventHandler((event: H3Event) => { + const url = event.node.req.url; + if (!url) { + return; + } + + // Only apply middleware to API routes + if (!url.startsWith("/api/")) { + return; + } + + // Bypass middleware for specific paths + if (url.startsWith("/api/map") || url.startsWith("/api/_auth/")) { + return; + } + + // Match the API key from the request with the app's API key + const requestApiKey = event.node.req.headers["x-api-key"]; + + if (requestApiKey !== appApiKey) { + throw createError({ + status: 403, + message: "Forbidden", + }); + } + }), +); diff --git a/src/utils/apiRequestValidator.ts b/src/utils/apiRequestValidator.ts deleted file mode 100644 index 0aae6f4..0000000 --- a/src/utils/apiRequestValidator.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { H3Event, createError, eventHandler } from "h3"; - -const apiRequestValidator = (appApiKey: string) => - eventHandler((event: H3Event) => { - const url = event.node.req.url; - if (!url) { - return; - } - - // Only apply middleware to API routes - if (!url.startsWith("/api/")) { - return; - } - - // Bypass middleware for specific paths - if (url.startsWith("/api/map") || url.startsWith("/api/_auth/")) { - return; - } - - // Match the API key from the request with the app's API key - const requestApiKey = event.node.req.headers["x-api-key"]; - - if (requestApiKey !== appApiKey) { - throw createError({ - status: 403, - message: "Forbidden", - }); - } - }); - -export default apiRequestValidator;