implemented rate limit and set up redis container
This commit is contained in:
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
from fastapi import Request
|
||||
|
||||
from src.cache.redis_client import redis_client
|
||||
from src.errors.http_errors.errors import Errors
|
||||
|
||||
|
||||
class RateLimit:
|
||||
def __init__(self) -> None:
|
||||
self.errors=Errors()
|
||||
|
||||
async def rate_limit(self, ip:str)->None:
|
||||
|
||||
key=f"action attempt {ip}"
|
||||
attempts = await redis_client.incrby(key)
|
||||
|
||||
if attempts == 1:
|
||||
await redis_client.expire(key, 60)
|
||||
|
||||
if attempts>5:
|
||||
raise self.errors.rate_limit_error(detail="too many attempts", retry_after=60)
|
||||
|
||||
async def check_rate_limit(self, request: Request) -> None:
|
||||
client_ip = request.headers.get('x-forwarded-for', '').split(',')[0].strip() or (request.client.host if request.client else 'unknown')
|
||||
await self.rate_limit(client_ip)
|
||||
|
||||
|
||||
rate_limiter=RateLimit()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user