Commit c803a1b9 authored by MariaV's avatar MariaV
Browse files

Merge branch 'ip_middleware' into 'master'

Custom Middleware for Django-Ratelimit with reverse proxy

See merge request !87
parents b5342122 a876bfa2
from django.core.validators import validate_ipv46_address
from django.core.exceptions import ValidationError
class XForwardedForMiddleware:
"""
Set REMOTE_ADDR if it's missing because of a reverse proxy (nginx + gunicorn) deployment.
https://stackoverflow.com/questions/34251298/empty-remote-addr-value-in-django-application-when-using-nginx-as-reverse-proxy
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if 'HTTP_X_FORWARDED_FOR' in request.META:
remote_addrs = request.META['HTTP_X_FORWARDED_FOR'].split(',')
remote_addr = None
# for some bots, 'unknown' was prepended as the first value: `unknown, ***.***.***.***`
# in which case the second value actually is the correct one
for ip in remote_addrs:
ip = self._validated_ip(ip)
if ip is not None:
remote_addr = ip
break
if remote_addr is None:
raise SuspiciousOperation('Malformed X-Forwarded-For.')
request.META['HTTP_X_PROXY_REMOTE_ADDR'] = request.META['REMOTE_ADDR']
request.META['REMOTE_ADDR'] = remote_addr
return self.get_response(request)
def _validated_ip(self, ip):
ip = ip.strip()
try:
validate_ipv46_address(ip)
except ValidationError:
return None
return ip
\ No newline at end of file
......@@ -46,6 +46,7 @@ INSTALLED_APPS = [
]
MIDDLEWARE = [
'shared.middleware.reverse_proxy_ip.XForwardedForMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment