-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement API request validation directly in server middleware
- Loading branch information
1 parent
07858a4
commit 87dde63
Showing
2 changed files
with
29 additions
and
36 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | ||
}); | ||
} | ||
}), | ||
); |
This file was deleted.
Oops, something went wrong.