Skip to content

Instantly share code, notes, and snippets.

@binki
Last active July 4, 2016 04:44
Show Gist options
  • Save binki/19e0820c743d2c76993f55c62152503f to your computer and use it in GitHub Desktop.
Save binki/19e0820c743d2c76993f55c62152503f to your computer and use it in GitHub Desktop.
Example of middleware for heroku forwarding
class ReverseProxy(object):
def process_request(self, request):
unsafe = True
try:
forwarded_for_split = [x.strip() for x in request.META['HTTP_X_FORWARDED_FOR'].split(',')]
# Client connecting to heroku’s stuff is the last listed one.
# http://stackoverflow.com/q/18264304/429091
request.META['REMOTE_ADDR'] = forwarded_for_split.pop()
unsafe = False
except KeyError:
pass
except IndexError:
pass
if unsafe:
raise Exception(
'You are attempting to use middleware for X-Forwarded-For in an environment'
+ ' which does not set X-Forwarded-For. This means that your server will *only*'
+ ' ever accept spoofed IPs. This configuration intentionally throws an exception'
+ ' because silently “handling” the error would be very insecure.')
# Fake out forwarded for by setting it to the remaining or unsetting if empty
if forwarded_for_split:
request.META['HTTP_X_FORWARDED_FOR'] = forwarded_for_split.join(',')
else:
del request.META['HTTP_X_FORWARDED_FOR']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment