Login

IP Authorization Decorator with IP list

Author:
jansta
Posted:
February 16, 2011
Language:
Python
Version:
Not specified
Tags:
IP Authorization Decorator
Score:
1 (after 1 ratings)

Improved version of http://djangosnippets.org/snippets/2205/

Example simple code: ` from django.http import HttpResponse IP_LIST = ['192.168.101.100', '192.168.101.220', '127.0.0.1', '127.0.1.1']

@ip_auth(IP_LIST) def get_parameter(request,name): parameter = get_object_or_404(Parameter,short_name=short_name) return HttpResponse(parameter.value)

`

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.http import HttpResponse

def ip_auth(authorised_ips):
    def inner(f):
        def authorization(*args,**kwargs):
            request = args[0]
            request_ip = request.META['REMOTE_ADDR']
            if request_ip not in authorised_ips:
                return HttpResponse(status=401)
            else:
                return f(*args, **kwargs)
        return authorization
    return inner

More like this

  1. IP Authorisation Decorator by pliskin 4 years, 5 months ago
  2. Decorator to limit request rates to individual views by jensbreit 6 years, 5 months ago
  3. Use memcached to throttle POSTs by coleifer 4 years, 9 months ago
  4. Django JSONP Decorator by cominatchu 4 years, 5 months ago
  5. HTTP headers view decorator by dottedmag 7 years, 8 months ago

Comments

darek (on February 16, 2011):

More generic:

def ip_auth(authorised_ips=None, banned_ips=None):
    def inner(f):
        def authorization(request, *args,**kwargs):
            authorised_ips = authorised_ips or getattr(settings, 'AUTHORISED_IPS', [])
            banned_ips = banned_ips or getattr(settings, 'BANNED_IPS', [])
            ip = request.META['REMOTE_ADDR']
            is_authorised = ip in authorised_ips if authorised_ips else True
            is_banned = ip in banned_ips
            if not is_authorised or is_banned:
                return HttpResponse(status=401)
            else:
                return f(request, *args, **kwargs)
        return authorization
    return inner

#

Please login first before commenting.