from django.conf import settings from django.core.exceptions import PermissionDenied from django.http import HttpResponsePermanentRedirect from django.urls import is_valid_path from django.utils.deprecation import MiddlewareMixin from django.utils.http import escape_leading_slashes class UnCommonMiddleware(MiddlewareMixin): """ Lol, common """ response_redirect_class = HttpResponsePermanentRedirect def process_request(self, request): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents user_agent = request.META.get('HTTP_USER_AGENT') if user_agent is not None: for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search(user_agent): raise PermissionDenied('Forbidden user agent') # Check for a redirect based on settings.PREPEND_WWW host = request.get_host() must_prepend = settings.PREPEND_WWW and host and not host.startswith('www.') redirect_url = ('%s://www.%s' % (request.scheme, host)) if must_prepend else '' # Check if a slash should be appended or removed if self.should_redirect_with_slash(request): path = self.get_full_path_with_slash(request) elif self.should_redirect_without_slash(request): path = self.get_full_path_without_slash(request) else: path = request.get_full_path() # Return a redirect if necessary if redirect_url or path != request.get_full_path(): redirect_url += path return self.response_redirect_class(redirect_url) def should_redirect_with_slash(self, request): """ Return True if settings.APPEND_SLASH is True and appending a slash to the request path turns an invalid path into a valid one. """ if settings.APPEND_SLASH and not request.path_info.endswith('/'): urlconf = getattr(request, 'urlconf', None) if not is_valid_path(request.path_info, urlconf): match = is_valid_path('%s/' % request.path_info, urlconf) if match: view = match.func return getattr(view, 'should_append_slash', True) return False def get_full_path_with_slash(self, request): """ Return the full path of the request with a trailing slash appended. Raise a RuntimeError if settings.DEBUG is True and request.method is POST, PUT, or PATCH. """ new_path = request.get_full_path(force_append_slash=True) # Prevent construction of scheme relative urls. new_path = escape_leading_slashes(new_path) if settings.DEBUG and request.method in ('POST', 'PUT', 'PATCH'): raise RuntimeError( "You called this URL via %(method)s, but the URL doesn't end " "in a slash and you have APPEND_SLASH set. Django can't " "redirect to the slash URL while maintaining %(method)s data. " "Change your form to point to %(url)s (note the trailing " "slash), or set APPEND_SLASH=False in your Django settings." % { 'method': request.method, 'url': request.get_host() + new_path, } ) return new_path def should_redirect_without_slash(self, request): """ Removing slashes, of course """ if settings.REMOVE_SLASH and request.path_info.endswith('/'): urlconf = getattr(request, 'urlconf', None) if not is_valid_path(request.path_info, urlconf): match = is_valid_path('%s' % request.path_info[:-1], urlconf) if match: view = match.func return getattr(view, 'should_remove_slash', True) return False def get_full_path_without_slash(self, request): """ z """ new_path = request.get_full_path(force_append_slash=True)[:-1] # Prevent construction of scheme relative urls. new_path = escape_leading_slashes(new_path) if settings.DEBUG and request.method in ('POST', 'PUT', 'PATCH'): raise RuntimeError( "You called this URL via %(method)s, but the URL doesn't end " "in a slash and you have APPEND_SLASH set. Django can't " "redirect to the slash URL while maintaining %(method)s data. " "Change your form to point to %(url)s (note the trailing " "slash), or set APPEND_SLASH=False in your Django settings." % { 'method': request.method, 'url': request.get_host() + new_path, } ) return new_path def process_response(self, request, response): """ When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True. """ # If the given URL is "Not Found", then check if we should redirect to # a path with a slash appended. if response.status_code == 404 and self.should_redirect_with_slash(request): return self.response_redirect_class(self.get_full_path_with_slash(request)) if response.status_code == 404 and self.should_redirect_without_slash(request): return self.response_redirect_class(self.get_full_path_without_slash(request)) # Add the Content-Length header to non-streaming responses if not # already set. if not response.streaming and not response.has_header('Content-Length'): response.headers['Content-Length'] = str(len(response.content)) return response