-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest_sanitize.py
53 lines (47 loc) · 2.03 KB
/
request_sanitize.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import logging
import json
import requests
from json import JSONDecodeError
from django.http import HttpResponseBadRequest
from urllib.parse import unquote
import bleach
logger = logging.getLogger(__name__)
class SanitizeMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def clean_dict(self, data):
for key, value in data.items():
if isinstance(value, dict):
data[key] = self.clean_dict(value)
else:
data[key] = bleach.clean(value)
return data
def __call__(self, request):
request.url = unquote(request.get_full_path())
if request.method == 'POST':
if request.content_type in ['application/json', 'application/json-patch+json']:
if len(request.POST) == 0:
try:
request_body = (request.body.decode("utf-8")).replace('\t', '').replace('\r\n', '')
if type(request_body) == str:
data = json.loads(request_body)
else:
data = request_body
except JSONDecodeError as e:
logger.warn("Unable to load JSON data in POST requests")
return HttpResponseBadRequest(content=f"Unable to load JSON data in POST requests".encode("utf-8"))
else:
data = request.POST
else:
logger.warn("Only JSON data is supported for POST requests")
return HttpResponseBadRequest(content=f"Only JSON data is supported for POST requests".encode("utf-8"))
for key, value in data.items():
data[key] = bleach.clean(value)
request.POST = data
elif request.method == 'GET':
params = request.GET.copy()
for key in params:
params[key] = bleach.clean(params[key])
request.GET = params
response = self.get_response(request)
return response