Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to use google recaptcha V3 in django

First I should say that I've read this, and It is not what I need. I want to have forms that I made with html/css not django forms.

And my method is based on this, that is actually in PHP.

I wrote code and it works fine, but I believe there should be a better way to do it.

The summery of code is that I submit my form, post the data and google recaptcha token to my function, and then do some process on it, then to redirect to the relative page base on results of processes, I return the url and status to jQuery again, and redirect to that page using jQuery.

Here is my code:

login.html:

<script src="https://www.google.com/recaptcha/api.js?render=here is recaptcha public key"></script>
<!-- login form and etc -->

<script>
$('#loginForm').submit(function() {
    // stop what loginform is going to do
    event.preventDefault();
    var username = $('#username').val();
    var password = $("#password").val();
    grecaptcha.ready(function () {
      grecaptcha.execute("here is recaptcha public key", 
         {action: "{% url 'basic_app:login_page' %}"}).then(function (token_id) 
              {$('#loginForm').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token_id + '">');
                $.post("{% url 'basic_app:login' %}",  // url
                   {username: username,password: password,
                    token_id: token_id,csrfmiddlewaretoken: '{{ csrf_token }}'},
                       function( result ){
                            console.log(result);
                            if(result.status == 0) {
                                    window.location.replace(result.url)
                            } else if (result.status == 1){
                                    window.location.replace(result.url)
                            }
                        },
                'json');
          });
      });
  });

views.py:

def user_login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        token_id = request.POST.get('token_id')
        if(token_id):
            secretKey = "here is recaptcha secret key"
            data = {
                'secret': secretKey,
                'response': token
            }
            r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
            result = r.json()
            ....
            ## some codes for more security 
            ....
            response = {'status': 0, 'message':"", 'url': '/'}
            return HttpResponse(json.dumps(response), content_type='application/json')
        else:
            response = {'status': 0, 'message':"", 'url': '/login_page'}
            return HttpResponse(json.dumps(response), content_type='application/json')     

....

is there any security problem in this method ?
and is there any way to write a better code to use recaptcha V3 ? thank you.

like image 512
hossein hayati Avatar asked Mar 04 '19 03:03

hossein hayati


People also ask

Is reCAPTCHA v3 better than v2?

Is reCAPTCHA v3 better than v2? Neither of them is good at blocking bots. While reCAPTCHA v3 is less intrusive than v2 for a user, it places a significant burden on the webmaster to determine when to let users through and when to block or challenge them. There's no right answer to this.

How do I integrate v3 reCAPTCHA?

Register your website and get Secret Key Very first thing you need to do is register your website on Google reCAPTCHA to do that click here. Login to your Google account and create the app by filling the form. Select the reCAPTCHA v3 and in that select the “I am not a robot” checkbox option.

Can I run reCAPTCHA v2 and v3 on the same page?

Yes, you can use both reCAPTCHA (non-Enterprise version) and reCAPTCHA Enterprise. Typically the third party solution asks for your public key and either your secret key or your API key.


1 Answers

Better steps:

  1. When user click submit, prevent default behaviour
  2. inside onSubmit, execute the g-recaptcha and store token inside form
  3. the call this.submit() or form.submit() like in the tutorial below
  4. validate the captcha in your view.

How to Implement Google Recaptcha v3 on your django app

like image 183
Muhammad Ihfazhillah Avatar answered Nov 10 '22 13:11

Muhammad Ihfazhillah