-
Alexa Valentová authoredAlexa Valentová authored
middlewares.py 1.32 KiB
from io import BytesIO
import clamd
from django.conf import settings
from django.http import HttpResponseForbidden
class ClamAVMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
# If there is no Clamd connection set, don't check files as we are presumably
# in a development environment.
if not settings.CLAMD_TCP_SOCKET or not settings.CLAMD_TCP_ADDR:
return self.get_response(request)
cd = clamd.ClamdNetworkSocket(
host=settings.CLAMD_TCP_ADDR, port=settings.CLAMD_TCP_SOCKET, timeout=120
)
if request.method == "POST" and len(request.FILES) > 0:
for file_ in request.FILES.values():
scan_result = cd.instream(BytesIO(file_.read()))
if scan_result["stream"][0] == "FOUND":
return HttpResponseForbidden(
"Nahraný soubor obsahuje potenciálně škodlivý obsah."
)
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response