fix(auth): validate API key from POST body and handle content type
- Switch API key validation to use POST body parameters - Add support for `application/x-www-form-urlencoded` content type - Store parsed body in context state for further use - Reject unsupported content types with 415 status
This commit is contained in:
@@ -2,17 +2,25 @@ import { Middleware } from 'http-kernel/Types/mod.ts';
|
||||
import { Env } from './env.ts';
|
||||
|
||||
/**
|
||||
* Middleware that checks for a valid API key via ?apiKey=... query/form param.
|
||||
* Rejects request with 403 if the key is missing or invalid.
|
||||
* Middleware that checks for a valid API key via form param.
|
||||
* Also stores the body in ctx.state.body for later use.
|
||||
*/
|
||||
export const authMiddleware: Middleware = async (ctx, next) => {
|
||||
const key = ctx.query.apiKey;
|
||||
const contentType = ctx.req.headers.get('content-type') || '';
|
||||
|
||||
// Support both ?apiKey=... and form body with apiKey=...
|
||||
const extractedKey = Array.isArray(key) ? key[0] : key;
|
||||
if (contentType.includes('application/x-www-form-urlencoded')) {
|
||||
const bodyBuffer = await ctx.req.arrayBuffer();
|
||||
ctx.state.body = new Uint8Array(bodyBuffer);
|
||||
|
||||
if (!extractedKey || !Env.apiKeys.includes(extractedKey)) {
|
||||
return new Response('Forbidden – Invalid API key', { status: 403 });
|
||||
const text = new TextDecoder().decode(ctx.state.body as Uint8Array);
|
||||
const params = new URLSearchParams(text);
|
||||
const key = params.get('apiKey');
|
||||
|
||||
if (!key || !Env.apiKeys.includes(key)) {
|
||||
return new Response('Forbidden – Invalid API key', { status: 403 });
|
||||
}
|
||||
} else {
|
||||
return new Response('Unsupported content type', { status: 415 });
|
||||
}
|
||||
|
||||
return await next();
|
||||
|
Reference in New Issue
Block a user