Skip to content

Commit

Permalink
fix: rate limit backend code status
Browse files Browse the repository at this point in the history
  • Loading branch information
ClementNumericite committed Sep 25, 2023
1 parent 4de3d5e commit 55c3901
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 19 deletions.
9 changes: 6 additions & 3 deletions webapp-next/pages/api/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,11 @@ export default async function handler(
: req.socket.remoteAddress;

// Rate limiting to prevent brute force auth
await limiter.check(res, 5, userIp as string); // 5 requests max per minute

try {
await limiter.check(res, 5, userIp as string); // 5 requests max per minute
} catch (e: any) {
return res.status(e.statusCode).end(e.message);
}
const client = new Client({
node: process.env.ELASTIC_HOST,
auth: {
Expand Down Expand Up @@ -85,7 +88,7 @@ export default async function handler(
res.status(200).send({ response: 'ok' });
}
} catch (error: any) {
console.log(error);
// console.log(error);
if (error.statusCode === 401) {
res.status(401).end();
} else {
Expand Down
34 changes: 18 additions & 16 deletions webapp-next/utils/rate-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,36 @@ import type { NextApiResponse } from 'next';
import { LRUCache } from 'lru-cache';

type Options = {
uniqueTokenPerInterval?: number
interval?: number
}
uniqueTokenPerInterval?: number;
interval?: number;
};

export default function rateLimit(options?: Options) {
const tokenCache = new LRUCache({
max: options?.uniqueTokenPerInterval || 500,
ttl: options?.interval || 60000,
})
ttl: options?.interval || 60000
});

return {
check: (res: NextApiResponse, limit: number, token: string) =>
new Promise<void>((resolve, reject) => {
const tokenCount = (tokenCache.get(token) as number[]) || [0]
const tokenCount = (tokenCache.get(token) as number[]) || [0];
if (tokenCount[0] === 0) {
tokenCache.set(token, tokenCount)
tokenCache.set(token, tokenCount);
}
tokenCount[0] += 1
tokenCount[0] += 1;

const currentUsage = tokenCount[0]
const isRateLimited = currentUsage >= limit
res.setHeader('X-RateLimit-Limit', limit)
const currentUsage = tokenCount[0];
const isRateLimited = currentUsage >= limit;
res.setHeader('X-RateLimit-Limit', limit);
res.setHeader(
'X-RateLimit-Remaining',
isRateLimited ? 0 : limit - currentUsage
)
);

return isRateLimited ? reject() : resolve()
}),
}
}
return isRateLimited
? reject({ statusCode: 429, message: 'Too many requests' })
: resolve();
})
};
}

0 comments on commit 55c3901

Please sign in to comment.