Date: 2018-11-21 17:20:02
Invisible ReCaptcha Django
Invisible ReCaptcha Django

Invisible ReCaptcha Django

There are some libraries for Django which you can use for this however, I prefer to do it by myself as it is more transparent and customizable (and in my case easier). To implement an invisible ReCaptcha by yourself using Django you start by using an official Google documentation:

Here you have plenty of information on how to implement it on the front end. This means you only have to add a button with some crucial parameters like:

Then in the js function onClickResetPassValid() you can do the validation of the input data as this is called if the recaptcha is successful.

Next, we need to verify this request in the back-end before continuing using the usual code which uses a return field in the POST request named g-recaptcha-response:

''' Begin reCAPTCHA validation '''
recaptcha_response = request.POST.get('g-recaptcha-response')
url = 'https://www.google.com/recaptcha/api/siteverify'
values = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
data = urllib.parse.urlencode(values).encode()
req = urllib.request.Request(url, data=data)

response = urllib.request.urlopen(req)
result = json.loads(response.read().decode())
''' End reCAPTCHA validation '''
if result['success'] == False:
context = {'recaptchaSuccess': False}
return render(request, 'login/login.html', context)

PROBLEMS?

Important to mention here is that if using validation in the front-end, there are some troubles and an approach mentioned in the first link (google documentation) should be used which is optimal. This approach would first validate the input data and after that use ReCaptcha validation.

However, we solved this problem differently as it suited our approach more. First, the reason for problems is that we need to reset the recaptcha after first calling the validation js function (e.g. onClickResetPassValid()) as the data-callback function can only be called once in the session if not reset. Therefore when we first call the validation function and possibly find a problem with data so that we do not submit the form, the button will not work for the second time (when we correct the data) as the recaptcha needs to be reset for the data-callback fuction to work again! This is done by using grecaptcha.reset() as mentioned here:

Calling grecaptcha.reset() should be implemented everytime the problem is detected in the js so that the ReCaptcha is reset and can work when the data is corrected. Example of this:

if (emailCond){
$("#divCheckEmailLogin").slideUp("fast");
$("#email").removeClass("inputWrongBorderRed");
}
else {
// reset recaptcha to try again!
grecaptcha.reset();
$("#divCheckEmailLogin").slideDown("fast");
$("#email").addClass("inputWrongBorderRed");
}
Designed and Developed with ♥︎
Copyright © 2018 VALUS - All Rights Reserved