mirror of
https://github.com/hex248/sprint.git
synced 2026-02-08 10:33:01 +00:00
ratelimiting via "withRateLimit"
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import type { BunRequest } from "bun";
|
||||
import { getSession } from "../db/queries";
|
||||
import { GLOBAL_RATE_LIMIT, getClientIP, rateLimitResponse, recordRateLimitAttempt } from "./rate-limit";
|
||||
import { parseCookies, verifyToken } from "./utils";
|
||||
|
||||
export type AuthedRequest<T extends BunRequest = BunRequest> = T & {
|
||||
@@ -19,6 +20,19 @@ const extractTokenFromCookie = (req: Request) => {
|
||||
return cookies.token || null;
|
||||
};
|
||||
|
||||
export const withRateLimit = <T extends BunRequest>(handler: RouteHandler<T>): RouteHandler<T> => {
|
||||
return async (req: T) => {
|
||||
const ip = getClientIP(req);
|
||||
const key = `global:ip:${ip}`;
|
||||
const attempt = recordRateLimitAttempt(key, GLOBAL_RATE_LIMIT);
|
||||
if (!attempt.allowed) {
|
||||
return rateLimitResponse(attempt.retryAfterMs);
|
||||
}
|
||||
|
||||
return handler(req);
|
||||
};
|
||||
};
|
||||
|
||||
export const withAuth = <T extends BunRequest>(handler: AuthedRouteHandler<T>): RouteHandler<T> => {
|
||||
return async (req: T) => {
|
||||
const token = extractTokenFromCookie(req);
|
||||
|
||||
Reference in New Issue
Block a user