From fa88fa658e2365138ece5c1b66826d5fd0c7330b Mon Sep 17 00:00:00 2001 From: Ashhhleyyy Date: Mon, 11 Mar 2024 18:18:49 +0000 Subject: [PATCH] feat(backend): block generic user agents --- backend/aci/utils.py | 5 +++++ backend/app.py | 11 ++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/backend/aci/utils.py b/backend/aci/utils.py index 846850e..2255d18 100644 --- a/backend/aci/utils.py +++ b/backend/aci/utils.py @@ -1,6 +1,11 @@ #!/usr/bin/env python3 from datetime import datetime +BAD_BOTS = [ + 'undici', + 'curl/(.*)', +] + def today() -> str: now = datetime.now() return format_checkin_date(now) diff --git a/backend/app.py b/backend/app.py index 2fcb6ad..124cb74 100644 --- a/backend/app.py +++ b/backend/app.py @@ -2,9 +2,10 @@ from typing import Union import hashlib +import re import sqlite3 -from fastapi import Depends, FastAPI +from fastapi import Depends, FastAPI, Request, Response from fastapi.middleware.cors import CORSMiddleware import uvicorn @@ -24,6 +25,14 @@ app.add_middleware( allow_headers="*", ) +@app.middleware('http') +async def badbots_block(req: Request, call_next): + ua = req.headers.get('User-Agent', '') + for bot in utils.BAD_BOTS: + if re.match(bot, ua): + return Response('forbidden', status_code=403) + return await call_next(req) + @app.get('/') def index(): return {