antibot-forms / forms.py

import random
import hashlib
from django.conf import settings
from django.core.cache import cache
from django.utils.safestring import mark_safe

class myForm(object):
    def __init__(self, request):
        self.form = {}
        self.request = request
        self.auth = ""
        self.posted = False
    def genName(self):
        dat = ""
        for i in range(0,9):
            dat += chr(random.randint(65,90))
        return dat
    def addField(self, typ, key, value=''):
        self.form[key] = {'type':typ, 'value':value, 'name':self.genName()}
        self.auth += key
    def setValue(self, key, value):
        self.form[key]['value'] = value
    def __getitem__(self, item):
        if item in self.form:
            self.request.session[item] = self.form[item]['name']
            if self.form[item]['type'] == 'textarea':
                return mark_safe('<textarea name="%s" id="id_comment" cols="80" rows="10">%s</textarea>' % (self.form[item]['name'], self.form[item]['value']))
            return mark_safe('<input name="%s" value="%s" type="%s" />' % (self.form[item]['name'], self.form[item]['value'], self.form[item]['type']))
        if item == 'auth':
            hash = hashlib.md5(self.auth+settings.SECRET_KEY).hexdigest()
            cache_key = self.genName()
            cache.set(cache_key, hash, 600)
            self.request.session[item] = cache_key
            return mark_safe('<input type="hidden" name="auth" value="%s" />' % hash)
        raise KeyError
    def is_valid(self):
        self.posted = True
        if self.request.method == 'GET':
            self.error = "Use POST method"
            return False
        if 'auth' not in self.request.session:
            self.error = "auth not in session"
            return False
        cache_key = self.request.session['auth']
        cache_auth = cache.get(cache_key, 'expired')
        for key in self.form:
            if key not in self.request.session:
                self.error = "%s not in session" % key
                return False
            self.form[key]['name'] = self.request.session[key]
            del self.request.session[key]
            if self.form[key]['name'] not in self.request.POST:
                self.error = "%s not in POST data." % self.form[key]['name']
                return False
            self.form[key]['value'] = self.request.POST[self.form[key]['name']]
        if cache_auth == 'expired':
            self.error = "Token expired, you have exactly 10 minutes to fill in a comment."
            return False
        if self.request.POST['auth'] != cache_auth:
            self.error = "Auth doesn't match Token."
            return False
        return True
    def getField(self, key):
        return self.request.POST[self.form[key]['name']]
    def getFields(self):
        post_vars = {}
        for key in self.form:
            post_vars[key] = self.request.POST[self.form[key]['name']]
            if post_vars[key] == '': del post_vars[key]
        return post_vars

def CommentForm(req, initial=None):
    frm = myForm(req)
    frm.addField('hidden', 'next')
    frm.addField('hidden', 'content_type')
    frm.addField('hidden', 'object_pk')
    frm.addField('hidden', 'timestamp')
    frm.addField('hidden', 'security_hash')
    frm.addField('text', 'name')
    frm.addField('text', 'email')
    frm.addField('text', 'url')
    frm.addField('textarea', 'comment')
    frm.addField('hidden','honeypot')
    if initial is not None:
        for key in initial:
            frm.setValue(key, initial[key])
    return frm
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.