Remove HTTP prefix from Django-style headers

Remove right_most_proxy because it's outside spec
This commit is contained in:
David Tan 2017-10-19 17:05:38 -04:00
parent bdf66cbb3f
commit dee2fc1fcc
2 changed files with 15 additions and 22 deletions

View File

@ -1,16 +1,15 @@
import socket
# CAPS R OK BCUZ STR.CASEFOLD
# CAPS R OK BCUZ WE HAZ CIDict
HEADER_PRECEDENCE_ORDER = (
'HTTP_X_FORWARDED_FOR', 'X_FORWARDED_FOR',
# (client, proxy1, proxy2) OR (proxy2, proxy1, client)
'HTTP_CLIENT_IP',
'HTTP_X_REAL_IP',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'HTTP_VIA',
'X_FORWARDED_FOR',
'CLIENT_IP',
'X_REAL_IP',
'X_FORWARDED',
'X_CLUSTER_CLIENT_IP',
'FORWARDED_FOR',
'FORWARDED',
'VIA',
'REMOTE_ADDR',
)

View File

@ -167,23 +167,17 @@ class Request(dict):
return self._cookies
@property
def ip(self, right_most_proxy=False):
# Need attr to differentiate the right_most_proxy thing
# Or we could use a separate method for right_most_proxy
attr = f'_ip{right_most_proxy}'
if not hasattr(self, attr):
setattr(self, attr, None)
def ip(self):
if not hasattr(self, '_ip'):
self._ip = None
for key in HEADER_PRECEDENCE_ORDER:
value = self.headers.get(key, self.headers.get(key.replace('_', '-'), '')).strip()
if value is not None and value != '':
ips = [ip.strip().lower() for ip in value.split(',')]
if right_most_proxy and len(ips) > 1:
ips = reversed(ips)
for ip_str in ips:
for ip_str in [ip.strip().lower() for ip in value.split(',')]:
if ip_str and is_valid_ip(ip_str):
if not ip_str.startswith(NON_PUBLIC_IP_PREFIX):
setattr(self, attr, ip_str)
return getattr(self, attr)
self._ip = ip_str
return self._ip
@property
def remote_addr(self):