Source

django-doorkeeper / doorkeeper / middleware.py

# -*- coding: utf-8 -*-
# Creation date: 10.03.12

import datetime

from django.http import Http404
from doorkeeper.models import BotRecord
from django.conf import settings

PATIENCE= getattr(settings,'DOORKEEPER_PATIENCE', 5)

class DoorkeeperMiddleware(object):
    def process_request(self, request):
        """
          Each request is investigated - overheads for suspicions
        """
        sagent = request.META.get('HTTP_USER_AGENT',"n/a")
        saddr = request.META.get('REMOTE_ADDR',"n/a")
        shash = "%s %s"% (saddr, sagent)
        try:
            br=BotRecord.objects.get(bot_hash=shash) # if client exists in BotRecords
            now=datetime.datetime.now()
            if br.detention_upto:                    # check detention end time
                if br.detention_upto> now:           # if it is a fresh banned client
                    raise Http404()                  # bounce - it's active bad bot!
                else:
                    if br.penalty_count > PATIENCE:  # for old banned client
                        br.penalty_count-=PATIENCE   # forgiving them partly
                        br.save()
                    pass
        except BotRecord.DoesNotExist:
            pass