hossein hayati
hossein hayati

Reputation: 1158

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.

Upvotes: 6

Views: 6849

Answers (1)

Muhammad Ihfazhillah
Muhammad Ihfazhillah

Reputation: 364

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

Upvotes: 1

Related Questions