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 import socket
# CAPS R OK BCUZ STR.CASEFOLD # CAPS R OK BCUZ WE HAZ CIDict
HEADER_PRECEDENCE_ORDER = ( HEADER_PRECEDENCE_ORDER = (
'HTTP_X_FORWARDED_FOR', 'X_FORWARDED_FOR', 'X_FORWARDED_FOR',
# (client, proxy1, proxy2) OR (proxy2, proxy1, client) 'CLIENT_IP',
'HTTP_CLIENT_IP', 'X_REAL_IP',
'HTTP_X_REAL_IP', 'X_FORWARDED',
'HTTP_X_FORWARDED', 'X_CLUSTER_CLIENT_IP',
'HTTP_X_CLUSTER_CLIENT_IP', 'FORWARDED_FOR',
'HTTP_FORWARDED_FOR', 'FORWARDED',
'HTTP_FORWARDED', 'VIA',
'HTTP_VIA',
'REMOTE_ADDR', 'REMOTE_ADDR',
) )

View File

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