Created
June 12, 2015 12:47
-
-
Save lukasklein/cfbc2706f8810352d35a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
def get_client_ip(request): | |
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') | |
if x_forwarded_for: | |
ip = x_forwarded_for.split(',')[0] | |
else: | |
ip = request.META.get('REMOTE_ADDR') | |
return ip | |
def test_ip_in_range(request): | |
client_ip = get_client_ip(request) | |
byte_to_bits = lambda b: bin(int(b))[2:].rjust(8, '0') | |
ip_to_bits = lambda ip: ''.join([byte_to_bits(b) for b in ip.split('.')]) | |
client_ip_bits = ip_to_bits(client_ip) | |
for net in settings.GITHUB_WEBHOOK_IPS: | |
ip, snet = net.split('/') | |
ip_bits = ip_to_bits(ip) | |
if client_ip_bits[:int(snet)] == ip_bits[:int(snet)]: | |
return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment