Skip to content

Commit 0137970

Browse files
committed
Merge pull request #1796 from rtfd/proxy-middleware
Add middleware to proper set REMOTE_ADDR
2 parents b086319 + 8d3ab48 commit 0137970

File tree

3 files changed

+28
-32
lines changed

3 files changed

+28
-32
lines changed

readthedocs/core/middleware.py

+27
Original file line numberDiff line numberDiff line change
@@ -162,3 +162,30 @@ def process_request(self, request):
162162
)
163163

164164
return None
165+
166+
167+
# Forked from old Django
168+
class ProxyMiddleware(object):
169+
170+
"""
171+
Middleware that sets REMOTE_ADDR based on HTTP_X_FORWARDED_FOR, if the
172+
latter is set. This is useful if you're sitting behind a reverse proxy that
173+
causes each request's REMOTE_ADDR to be set to 127.0.0.1.
174+
Note that this does NOT validate HTTP_X_FORWARDED_FOR. If you're not behind
175+
a reverse proxy that sets HTTP_X_FORWARDED_FOR automatically, do not use
176+
this middleware. Anybody can spoof the value of HTTP_X_FORWARDED_FOR, and
177+
because this sets REMOTE_ADDR based on HTTP_X_FORWARDED_FOR, that means
178+
anybody can "fake" their IP address. Only use this when you can absolutely
179+
trust the value of HTTP_X_FORWARDED_FOR.
180+
"""
181+
182+
def process_request(self, request):
183+
try:
184+
real_ip = request.META['HTTP_X_FORWARDED_FOR']
185+
except KeyError:
186+
return None
187+
else:
188+
# HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs. The
189+
# client's IP will be the first one.
190+
real_ip = real_ip.split(",")[0].strip()
191+
request.META['REMOTE_ADDR'] = real_ip

readthedocs/core/underscore_middleware.py

-32
This file was deleted.

readthedocs/settings/base.py

+1
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@
103103
)
104104

105105
MIDDLEWARE_CLASSES = (
106+
'readthedocs.core.middleware.ProxyMiddleware',
106107
'django.contrib.sessions.middleware.SessionMiddleware',
107108
'django.middleware.locale.LocaleMiddleware',
108109
'django.middleware.common.CommonMiddleware',

0 commit comments

Comments
 (0)