34 lines
1.0 KiB
Python
34 lines
1.0 KiB
Python
import importlib
|
|
from asgiref.sync import iscoroutinefunction, markcoroutinefunction
|
|
|
|
from django.conf import settings
|
|
from django.http import HttpResponse
|
|
|
|
|
|
def load_backing_class(path: str):
|
|
mod_name, _, cls_name = path.rpartition(".")
|
|
module = importlib.import_module(mod_name)
|
|
return getattr(module, cls_name)
|
|
|
|
|
|
class AiBlockerMiddleware:
|
|
def __init__(self, get_response):
|
|
self.get_response = get_response
|
|
|
|
if iscoroutinefunction(self.get_response):
|
|
markcoroutinefunction(self)
|
|
|
|
self.backing_class = getattr(getattr(settings, "AI_BLOCKER_CONF"), "backing_class", "ai_blocker.ualist_backers.ConfigBackedUAList")
|
|
Backer = load_backing_class(self.backing_class)
|
|
self.backer = Backer()
|
|
|
|
async def __call__(self, request):
|
|
ua = request.headers.get("User-Agent", "")
|
|
|
|
|
|
if ua in self.backer:
|
|
return HttpResponse(status=403)
|
|
|
|
response = self.get_response(request)
|
|
# Add code here to process the response after the view has been run.
|
|
return response |