Skip to content

Commit

Permalink
Implement API request validation directly in server middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
rudokemper committed Sep 17, 2024
1 parent 07858a4 commit 87dde63
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 36 deletions.
34 changes: 29 additions & 5 deletions src/runtime/server/middleware/apiAuth.ts
Original file line number Diff line number Diff line change
@@ -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",
});
}
}),
);
31 changes: 0 additions & 31 deletions src/utils/apiRequestValidator.ts

This file was deleted.

0 comments on commit 87dde63

Please sign in to comment.