hobo/hobo/middleware/xforwardedfor.py

18 lines
685 B
Python

from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
class XForwardedForMiddleware(MiddlewareMixin):
"""Copy the first address from X-Forwarded-For header to the REMOTE_ADDR meta.
This middleware should only be used if you are sure the header cannot be
forged (behind a reverse proxy for example)."""
def process_request(self, request):
if getattr(settings, 'USE_X_FORWARDED_FOR', False):
if 'x-forwarded-for' in request.headers:
ip = request.headers.get('X-Forwarded-For', '').split(",")[0].strip()
if ip:
request.META['REMOTE_ADDR'] = ip
return None