From 9431e9846c9d88ed0ed7cd7ec9ffd370a32eae79 Mon Sep 17 00:00:00 2001 From: Andrii Marynets Date: Fri, 30 Jun 2017 08:44:39 +0300 Subject: [PATCH] Add middleware for fix "get_host() method fails when the host is behind multiple proxies" --- dynamicweb/settings/base.py | 4 +++- utils/middleware.py | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 utils/middleware.py diff --git a/dynamicweb/settings/base.py b/dynamicweb/settings/base.py index 31723853..08ed7fe5 100644 --- a/dynamicweb/settings/base.py +++ b/dynamicweb/settings/base.py @@ -118,6 +118,7 @@ INSTALLED_APPS = ( MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', + 'utils.middleware.MultipleProxyMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', @@ -515,5 +516,6 @@ DCL_SUPPORT_FROM_ADDRESS = env('DCL_SUPPORT_FROM_ADDRESS') # Settings for Google analytics GOOGLE_ANALYTICS_PROPERTY_IDS = { 'datacenterlight.ch': 'UA-62285904-9', - 'digitalglarus.ch': 'UA-62285904-2' + 'digitalglarus.ch': 'UA-62285904-2', + '127.0.0.1:8000': 'test' } diff --git a/utils/middleware.py b/utils/middleware.py new file mode 100644 index 00000000..d37bdbfd --- /dev/null +++ b/utils/middleware.py @@ -0,0 +1,17 @@ +class MultipleProxyMiddleware(object): + FORWARDED_FOR_FIELDS = [ + 'HTTP_X_FORWARDED_FOR', + 'HTTP_X_FORWARDED_HOST', + 'HTTP_X_FORWARDED_SERVER', + ] + + def process_request(self, request): + """ + Rewrites the proxy headers so that only the most + recent proxy is used. + """ + for field in self.FORWARDED_FOR_FIELDS: + if field in request.META: + if ',' in request.META[field]: + parts = request.META[field].split(',') + request.META[field] = parts[-1].strip() \ No newline at end of file