Login

User/IP Banning Middleware

Author:
justquick
Posted:
April 26, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

Banning middleware with allow,deny functionality. Can select by User id/username and IP addresses. Returns a HttpResponseForbidden when banning requests. Banning by users is real nice because no matter which IP a pest comes from, they can never retrieve anything that they log into. Very handy for keeping out those unwanted pests! I personally developed this further to use a Ban model to keep track of different bans on different sites. Maybe ill post that eventually, but this runs as is with static vars. Implementation from HvZ Source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
from django.http import HttpResponseForbidden
from django.contrib.auth.models import User

# SETUP THE VARS! all comma sep lists
# some vars you should override
allow_ips = '192.168.1.%' # ipaddr list, % is wildcard
allow_users = 'admin' # by username or id num
deny_ips = '%.%.%.%'
deny_users = 'AnonymousUser'
order = 'allow,deny' # either 'allow,deny' 'deny,allow' or any ONE of the choices
# a var you could override
forbid = HttpResponseForbidden("""
    <html>
    <head>
        <title>403 Forbidden</title>
    </head>
    <body>
        <h1>403 Forbidden</h1>
        <p>This resource is unavailable at this time from this computer.</p>
    </body>
    </html>""")
    
splits = lambda x: x.replace(' ','').split(',')
vsplits = lambda x: x.replace('%','').split('.')

def getIP(req):
    ip = req.META['REMOTE_ADDR']
    # forwarded proxy fix for webfaction
    if (not ip or ip == '127.0.0.1') and req.META.has_key('HTTP_X_FORWARDED_FOR'):
        ip = req.META['HTTP_X_FORWARDED_FOR']
    return ip 

def cmpIP(x,y): 
    # Returns boolean whether or not the ip matterns match, % is a wildcard  
    print x,y 
    x = vsplits(x); y = vsplits(y)
    for i in range(4): 
        if x[i] and y[i] and x[i] != y[i]:
            return False
    return True
    
def cmpU(x,y):
    # Do a similar cmp on users
    if x == '%': return True
    u = 'AnonymousUser'
    try: u = User.objects.get(pk=int(x))
    except: 
        try: u = User.objects.get(username=x)
        except: pass
    return u == str(y)
    
def action(xset,yval,mode='ip'):
    # Determine action on a user set and ip set
    print xset,yval,mode
    if mode == 'user':
        for x in xset:
            if x and cmpU(x,yval):
                return True
    elif mode == 'ip':                
        for x in xset:
            if x and cmpIP(x,yval):
                return True
    return False
    
class BanWare(object):
    def process_request(self, request):    
        # gather some info
        user = None
        if hasattr(request, 'user'):
            user = request.user
        elif request.session.has_key('_auth_user_id'):
            user = request.session['_auth_user_id']                 
        ip = getIP(request)

        allow = lambda:  action(splits(allow_users), user, mode='user') or \
             action(splits(allow_ips), ip)
        deny = lambda: action(splits(deny_users), user, mode='user') or \
            action(splits(deny_ips), ip)

        # depending on order, 1 if request is allowed, 0 if its denied
        ra = None
        opts = filter(None,splits(order)[:2])
        print opts
        print allow(),deny()
        if opts:
            for opt in opts:
                if opt=='allow' and allow():
                    ra = 1
                elif opt=='deny' and deny():
                    ra = 0
        else:
            if allow(): ra = 1
            elif deny(): ra = 0
        if not ra:
            # delete sessions when denied
            for k in request.session.keys():
                del request.session[k]
            return forbid

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.