26 lines
685 B
TypeScript
26 lines
685 B
TypeScript
|
|
import { getRequestIP, createError } from 'h3'
|
||
|
|
|
||
|
|
const attempts = new Map<string, { count: number; resetAt: number }>()
|
||
|
|
|
||
|
|
const WINDOW_MS = 15 * 60 * 1000
|
||
|
|
const MAX_ATTEMPTS = 10
|
||
|
|
|
||
|
|
export function checkRateLimit(event: any): void {
|
||
|
|
const ip = getRequestIP(event) || 'unknown'
|
||
|
|
const now = Date.now()
|
||
|
|
const record = attempts.get(ip)
|
||
|
|
|
||
|
|
if (record && now < record.resetAt) {
|
||
|
|
if (record.count >= MAX_ATTEMPTS) {
|
||
|
|
throw createError({
|
||
|
|
statusCode: 429,
|
||
|
|
statusMessage: 'Too Many Requests',
|
||
|
|
message: 'Too many attempts. Please try again later.',
|
||
|
|
})
|
||
|
|
}
|
||
|
|
record.count++
|
||
|
|
} else {
|
||
|
|
attempts.set(ip, { count: 1, resetAt: now + WINDOW_MS })
|
||
|
|
}
|
||
|
|
}
|