Captcha Middleware

 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. Captcha Middleware (Template) by zeeg 7 years ago
  2. captcha, verification code by dingdongquan 3 years, 3 months ago
  3. Include captchas from recaptcha.net by b23 6 years, 6 months ago
  4. Mathematical Captcha by dogada 6 years, 4 months ago
  5. HammeringMiddleware by pandoodl 3 years, 1 month 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?

#

(Forgotten your password?)