improved logging and implemented method to reduce response mac_address_length

This commit is contained in:
Oscar Krause 2024-11-22 14:16:10 +01:00
parent a43ddf79c3
commit 53c88a79ac

View File

@ -22,20 +22,40 @@ class PatchMalformedJsonMiddleware(BaseHTTPMiddleware):
content_type = request.headers.get('Content-Type') content_type = request.headers.get('Content-Type')
if self.enabled and content_type == 'application/json': if self.enabled and content_type == 'application/json':
logger.debug(f'Using Request-Patch because "PatchMalformedJsonMiddleware" is enabled!')
# try to fix json
body = body.decode() body = body.decode()
try: try:
json.loads(body) j = json.loads(body)
self.fix_mac_address_list_length(j=j, size=1)
except json.decoder.JSONDecodeError: except json.decoder.JSONDecodeError:
logger.warning(f'Malformed json received! Try to fix it, "PatchMalformedJsonMiddleware" is enabled.') logger.warning(f'Malformed json received! Try to fix it.')
s = PatchMalformedJsonMiddleware.fix_json(body) s = PatchMalformedJsonMiddleware.fix_json(body)
logger.debug(f'Fixed JSON: "{s}"') logger.debug(f'Fixed JSON: "{s}"')
s = json.loads(s) # ensure json is now valid j = json.loads(s) # ensure json is now valid
j = self.fix_mac_address_list_length(j=j, size=1)
# set new body # set new body
request._body = json.dumps(s).encode('utf-8') request._body = json.dumps(j).encode('utf-8')
response = await call_next(request) response = await call_next(request)
return response return response
def fix_mac_address_list_length(self, j: dict, size: int = 1) -> dict:
if not self.enabled:
return j
# reduce "mac_address_list" to
environment = j.get('environment', {})
fingerprint = environment.get('fingerprint', {})
mac_address = fingerprint.get('mac_address_list', [])
if len(mac_address) > 0:
logger.info(f'Transforming "mac_address_list" to length of {size}.')
j['environment']['fingerprint']['mac_address_list'] = mac_address[:size]
return j
@staticmethod @staticmethod
def fix_json(s: str) -> str: def fix_json(s: str) -> str:
s = s.replace('\t', '') s = s.replace('\t', '')