35 lines
1.4 KiB
Python
35 lines
1.4 KiB
Python
|
import django
|
||
|
from django.http import JsonResponse
|
||
|
from django.middleware.common import CommonMiddleware
|
||
|
from django.utils.translation import ugettext_lazy as _
|
||
|
|
||
|
|
||
|
class HoboCommonMiddleware(CommonMiddleware):
|
||
|
def __call__(self, *args, **kwargs):
|
||
|
self.will_redirect_with_slash = False
|
||
|
return super().__call__(*args, **kwargs)
|
||
|
|
||
|
def should_redirect_with_slash(self, request):
|
||
|
self.will_redirect_with_slash = super().should_redirect_with_slash(request)
|
||
|
return self.will_redirect_with_slash
|
||
|
|
||
|
def forbid_redirect(self, request, response):
|
||
|
return bool(
|
||
|
self.will_redirect_with_slash
|
||
|
and isinstance(response, self.response_redirect_class)
|
||
|
and request.path_info.startswith('/api/')
|
||
|
and request.method in ("POST", "PUT", "PATCH")
|
||
|
)
|
||
|
|
||
|
def process_request(self, request):
|
||
|
response = super().process_request(request)
|
||
|
if self.forbid_redirect(request, response):
|
||
|
return JsonResponse({'err': 1, 'err_desc': _('URL must end with a slash.')}, status=404)
|
||
|
return response
|
||
|
|
||
|
def process_response(self, request, response):
|
||
|
response = super().process_response(request, response)
|
||
|
if self.forbid_redirect(request, response):
|
||
|
return JsonResponse({'err': 1, 'err_desc': _('URL must end with a slash.')}, status=404)
|
||
|
return response
|