Protect anti robots template tag

  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
 99
100
101
102
103
104
# Middleware

import hmac, sha, base64, os

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.utils.translation import ugettext as _

class ProtectAntiRobotsMiddleware(object):
    def process_request(self, request):
        if request.get_full_path().startswith('/protectantirobots/'):
            if request.get_full_path() == '/protectantirobots/img/':
                s = base64.b64decode(request.session['protectantirobots_key'])
                size = (100,30)
                img = Image.new("RGB", size, "white")

                draw = ImageDraw.Draw(img)
                font = ImageFont.truetype(os.path.dirname(__file__)+"/FreeSansBold.ttf", 24)
                draw.text((2,2), s, fill="red", font=font)

                draw.line((0, 0) + img.size, fill=128)
                draw.line((0, img.size[1], img.size[0], 0), fill=128)
                del draw

                ret = HttpResponse(mimetype='image/gif')
                img.save(ret, "GIF")
                return ret
            elif 'k' in request.GET:
                if request.POST:
                    n = request.POST['n']
                    sec = base64.b64decode(request.session['protectantirobots_key'])
                    if n == sec:
                        request.session['protectantirobots_sec'] = sec
                        return HttpResponseRedirect(request.session['protectantirobots_referer'])
                    return render_to_response(
                        'protectantirobots.html',
                        {'msg': _('Invalid number!')},
                        context_instance=RequestContext(request),
                        )
                else:
                    request.session['protectantirobots_key'] = request.REQUEST['k']
                    request.session['protectantirobots_referer'] = request.META.get('HTTP_REFERER', '')
                    return render_to_response(
                        'protectantirobots.html',
                        locals(),
                        context_instance=RequestContext(request),
                        )

# Template tag

import base64
from datetime import datetime, timedelta

from django.template import Library, Node
from django.utils.translation import ugettext as _

class ProtectAntiRobotsNode(Node):
    nodelist = ''

    def __init__(self, nodelist):
        super(ProtectAntiRobotsNode, self).__init__()

        self.nodelist = nodelist

    def __repr__(self):
        return "<ProtectAntiRobotsNode>"

    def render(self, context):
        request = context['request']
        if 'protectantirobots_sec' in request.session and \
           'protectantirobots_key' in request.session:
            if request.session['protectantirobots_sec'] == base64.b64decode(request.session['protectantirobots_key']):
                output = self.nodelist.render(context)
                return output
        
        sec = base64.b64encode(datetime.now().strftime("%H%m%S"))
        return '<a href="%s">%s</a>' %(self.get_url(sec), _('Let us know if you are human'))

    def get_url(self, sec):
        return "/protectantirobots/?k=" + sec

def do_protectantirobots(parser, token):
    nodelist = parser.parse(('endprotectantirobots',))
    parser.delete_first_token()
    return ProtectAntiRobotsNode(nodelist)
do_protectantirobots= register.tag('protectantirobots', do_protectantirobots)

# Template (protectantirobots.html file) - you can change layout and other things

<html>
    <body>
        What number is this?
        <form method="post">
            <img src="/protectantirobots/img/"/>
            <input name="n"/>
            <input type="submit"/>
        </form>

        {% if msg %}
        <strong>{{ msg }}</strong>
        {% endif %}
    </body>
</html>

More like this

  1. YUI Loader as Django middleware by akaihola 5 years, 12 months ago
  2. Template Tag to protect the E-mail address by nitinhayaran 4 years, 2 months ago
  3. Simple random file CAPTCHA by jeverling 2 years, 1 month ago
  4. Confirm alert if the user navigates away without saving changes by mrazzari 4 years, 9 months ago
  5. whitespaceoptimize block tag by peterbe 5 years, 7 months ago

Comments

marinho (on August 12, 2008):

Fixed line 65 (not subscriptable request object)

#

(Forgotten your password?)