且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django-将Google Recaptcha v2添加到登录表单

更新时间:2023-12-03 21:56:40

直接帮助很困难,因为您没有提到要使用的库。这是我在Django登录中添加v2验证码的方法,不需要其他库。

It's difficult to directly help as you did not mention what library you were trying to use. Here is my approach to adding a v2 recaptcha to Django login, no additional libs required.

在此示例中,我将recaptcha脚本添加到django登录模板,并覆盖django auth应用程序的登录视图,以扩展其功能以验证Recaptcha服务器端(根据 google docs )。

In this example, I add the recaptcha script to the django login template, and override django auth app's login view, in order to extend its functionality such that it validates the recaptcha server side (with the appropriate RECAPTCHA_SECRET as per google docs).

还要注意,context_processor用于在登录模板中插入RECAPTCHA_SITE_KEY。

Also note that context_processor is used to insert the RECAPTCHA_SITE_KEY in the login template.

登录.html

...
<head>
   <script src="https://www.google.com/recaptcha/api.js" async defer</script>
<script>
  function onSubmit(token) {
    document.getElementById("theForm").submit();
  }
</script>
</head>
<body>
<form id="theForm">
<button class="g-recaptcha btn btn-primary" 
        data-callback="onSubmit" 
        data-sitekey="{{RECAPTCHA_SITE_KEY}}" 
        type="submit">Login
</button>
</form>
</body>
...

url.py

...
# overriding auth app endpoint 
url(r'^accounts/login/', MyLoginView.as_view(), name='login'),
...

context_processor.py

from django.conf import settings 


def recaptcha_site_key(request):
    return {'RECAPTCHA_SITE_KEY': settings.RECAPTCHA_SITE_KEY}

settings.py

TEMPLATES = [
  {
    ...
    'OPTIONS': {
        'context_processors': [
            ...
            'yourapp.context_processors.recaptcha_site_key',
            ...
        ],
    },
  },
]

MyLoginView.py

from django.contrib.auth import views as auth_views

def _validate_recaptcha(token, ip):
    # implement server side validation according to google docs
    pass    

class MyLoginView(auth_views.LoginView):
'''Edited per @avib answer
'''
    def post(self, form):

        request_body = self.request.POST
        if not request_body:
            return None
    
        recaptcha_token = request_body['g-recaptcha-response']
        ip_addr, _ = get_client_ip(self.request)
        if not _validate_recaptcha(recaptcha_token, ip_addr):
            # your logic
            return redirect('login')

    return super().post(form)