Login

Captcha Middleware

Author:
zeeg
Posted:
March 23, 2007
Language:
Python
Version:
.96
Score:
6 (after 6 ratings)

A middleware we are using to stop "spam" on Curse. It makes the user fill in a captcha box whenever they submit a form unless a cookie is set (which expires by default after 6 hours)

See also the template

Note: render_template is simply a shortcut function we have for doing render_to_response with a request context

 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
from random import randrange,randint
from Captcha.Visual.Tests import PseudoGimpy
import sys, datetime
from cursesite.utils.template import render_template
from django.core.validators import ValidationError
from django.conf import settings
from django.views.decorators.cache import cache_control

CAPTCHA_TIMEOUT = 360 # 360 minutes -- 6 hours

@cache_control(no_cache=True)
def show_captcha(request):
	from django.http import HttpResponse
	response = HttpResponse()
	response['Content-type'] = "image/png"
	g = PseudoGimpy()
	i = g.render()
 	i.save(response, "png")
 	safe_solutions = [hash(s) for s in g.solutions]
	response.set_cookie('captcha', safe_solutions, max_age=None, expires=None, 
		domain=settings.SESSION_COOKIE_DOMAIN)
	return response

class CaptchaMiddleware:
	def __init__(self):
		self.captcha_check = False
		
	def checkCaptcha(self, data):
		if not self.captcha_solutions:
			raise ValidationError, "Cookies required to register"
	
		if str(hash(data)) not in self.captcha_solutions:
			raise ValidationError, "Text incorrect"
			
	def process_request(self, request):
		if (request.user.is_authenticated() and (request.user.mobile_verified or request.user.is_staff)) or not settings.ENABLE_CAPTCHA:
			return
		if request.POST and ('_ish' not in request.COOKIES or datetime.datetime.fromtimestamp(float(request.COOKIES.get('_ish', 0))) < datetime.datetime.now()-datetime.timedelta(minutes=CAPTCHA_TIMEOUT)):
			error = None
			self.captcha_solutions = request.COOKIES.get('captcha', None)
			if 'captcha' in request.POST:
				try:
					self.checkCaptcha(request.POST.get('captcha'))
				except ValidationError, msg:
					print msg
					error = msg
				else:
					self.captcha_check = True
					return
			ec = {
				'error': error,
				'random_num': randint(1, sys.maxint),
				'url': request.path,
				'post_data': request.POST,
			}
			return render_template(request, 'captcha.html', ec)

	def process_response(self, request, response):
		from time import time
		if self.captcha_check:
			response.set_cookie('_ish', int(time()), max_age=None,
			expires=datetime.datetime.now()+datetime.timedelta(hours=CAPTCHA_TIMEOUT), 
			domain=settings.SESSION_COOKIE_DOMAIN)
		return response

More like this

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

Comments

polarbear (on April 12, 2007):

Please explain:

from cursesite.functions.template import render_template

What this function returns? Or supply code. Otherwise it doesn't work.

#

alaclp (on September 18, 2008):

This is a very good article.And I used this middleware in my test project. But how to check whether it is right for a user's input text? Can give me a example?

#

Please login first before commenting.