OLD | NEW |
(Empty) | |
| 1 # Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is govered by a BSD-style |
| 3 # license that can be found in the LICENSE file or at |
| 4 # https://developers.google.com/open-source/licenses/bsd |
| 5 |
| 6 """A simple python interface to ReCAPTCHA.""" |
| 7 |
| 8 import json |
| 9 import logging |
| 10 import urllib |
| 11 import urllib2 |
| 12 |
| 13 from services import secrets_svc |
| 14 |
| 15 def Verify(remote_ip, response): |
| 16 """Check the user's guess at a captcha solution. |
| 17 |
| 18 Args: |
| 19 remote_ip: user's IP address. |
| 20 challenge: The captcha challenge presented to the user. |
| 21 guess: The user's response to the captcha. |
| 22 |
| 23 Returns: |
| 24 A pair (correct, error_msg) where error_msg will indicate |
| 25 why a response was deemed incorrect. It is logged so that |
| 26 you can see, e.g., if you have the wrong private key. |
| 27 """ |
| 28 # If the use did not enter anything, that is always incorrect |
| 29 if not response: |
| 30 logging.info('response was blank') |
| 31 return False, 'incorrect-captcha-sol' |
| 32 |
| 33 resp = _AskRecaptcha(remote_ip, response) |
| 34 if not resp['success']: |
| 35 if 'error-codes' in resp: |
| 36 return False, resp['error-codes'] |
| 37 else: |
| 38 return False, 'incorrect-captcha-sol' |
| 39 |
| 40 return True, '' |
| 41 |
| 42 def _AskRecaptcha(remote_ip, response): |
| 43 """Ask the ReCAPTCHA backend to verify the user's guess.""" |
| 44 recaptcha_server_request = urllib2.Request( |
| 45 url='https://www.google.com/recaptcha/api/siteverify', |
| 46 data=urllib.urlencode({ |
| 47 'secret': secrets_svc.GetRecaptchaPrivateKey(), |
| 48 'remoteip': remote_ip, |
| 49 'response': response}), |
| 50 headers={ |
| 51 'Content-type': 'application/x-www-form-urlencoded', |
| 52 'User-agent': 'reCAPTCHA Python'}) |
| 53 recaptcha_server_response = urllib2.urlopen(recaptcha_server_request) |
| 54 resp = json.loads(recaptcha_server_response.read()) |
| 55 recaptcha_server_response.close() |
| 56 |
| 57 return resp |
| 58 |
OLD | NEW |