There are a few parts to the puzel
1. The form must contains two extra fields as follows:
1.1 A field that will display the reCaptcha icon and checkbox
This filed can be added to the template where you want to display the captcha (I add it just after the [[=form]] . This field will take care of displaying
the captcha UI automatically. Nothing here for you to do (I think you change the 'I am not a Robot' language. see google,docs)
<div class="g-recaptcha" data-sitekey="YOUR-CAPTCHAT-SITE-KEY"></div>
1.2 When the user check the checkbox, If successfule, Captcha server(google) sends a long confirmation string and put it
in the second field, which you should add to the form in a way that it will be returned to the controller when the form is submitted
I did it by adding this line to the controller just befor the controller returns the dict containing the forrm object:
form.structure.insert(0, INPUT(_name='captcha_data',_id='captcha_data', _hidden=True, _value='a'))
(may be there are other ways to do it)
This make sure that the field is returned to the controller and you can validate the information.
2. Validating the information
2.1 I do it by adding a validation=validate_user_form when creating the form by calling form = FORM(.... validation=validate_user_form ) in the controller.
You will need to write the validate_user_form() function in order to validate the captcha.
2.2 Validation the captcha data
def validate_user_form(form):
if verify_captcha(form.vars['captcha_data']):
return
form.errors['comment'] ="You are probably a Robot"
2.3 .. And the verify_captcha() looks like:
def verify_captcha(captchaData=None):
if captchaData is None:
return False
data = {"secret": "YOUR-SECRET-CAPTHA-KEY", "response": captchaData}
res = requests.post("https://www.google.com/recaptcha/api/siteverify", data=data)
try:
if res.json()["success"]:
return True
except Exception as exc:
pass
return False
Thats it !
Let me know if you need mor information