]> git.openstreetmap.org Git - osqa.git/blob - forum_modules/recaptcha/lib/captcha.py
general improvements of the recaptcha client
[osqa.git] / forum_modules / recaptcha / lib / captcha.py
1 # -*- coding: utf-8 -*-
2
3 import urllib2, urllib
4
5 API_SSL_SERVER="https://www.google.com/recaptcha/api"
6 API_SERVER="http://www.google.com/recaptcha/api"
7 VERIFY_SERVER="www.google.com"
8
9 class RecaptchaResponse(object):
10     def __init__(self, is_valid, error_code=None):
11         self.is_valid = is_valid
12         self.error_code = error_code
13
14 def displayhtml (public_key):
15
16     return """
17     <div id="recaptcha_field"></div>
18     <script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
19
20     <script type="text/javascript">
21          $(function(){
22              Recaptcha.create("%(PublicKey)s", 'recaptcha_field', {
23              theme: "red",
24              callback: Recaptcha.focus_response_field});
25          });
26     </script>
27
28 """ % {
29         'PublicKey' : public_key,
30         }
31
32
33 def submit (recaptcha_challenge_field,
34             recaptcha_response_field,
35             private_key,
36             remoteip):
37
38     if not (recaptcha_response_field and recaptcha_challenge_field and
39             len (recaptcha_response_field) and len (recaptcha_challenge_field)):
40         return RecaptchaResponse (is_valid = False, error_code = 'incorrect-captcha-sol')
41
42
43     def encode_if_necessary(s):
44         if isinstance(s, unicode):
45             return s.encode('utf-8')
46         return s
47
48     params = urllib.urlencode ({
49         'privatekey': encode_if_necessary(private_key),
50         'remoteip' :  encode_if_necessary(remoteip),
51         'challenge':  encode_if_necessary(recaptcha_challenge_field),
52         'response' :  encode_if_necessary(recaptcha_response_field),
53         })
54
55     request = urllib2.Request (
56         url = "http://%s/recaptcha/api/verify" % VERIFY_SERVER,
57         data = params,
58         headers = {
59             "Content-type": "application/x-www-form-urlencoded",
60             "User-agent": "reCAPTCHA Python"
61         }
62     )
63
64     httpresp = urllib2.urlopen(request)
65
66     return_values = httpresp.read().splitlines()
67     httpresp.close()
68
69     return_code = return_values[0]
70
71     if return_code == "true":
72         return RecaptchaResponse(is_valid = True)
73     else:
74         return RecaptchaResponse(is_valid = False, error_code = return_values[1])