hos*_*ati 6 python django jquery recaptcha
首先我应该说我已经读过了,这不是我所需要的。我想使用html / css而不是Django表单制作表单。
而且我的方法基于此,实际上是在PHP中。
我编写了代码,并且运行良好,但是我相信应该有更好的方法来实现。
代码的总结是,我提交表单,将数据和google recaptcha令牌发布到我的函数中,然后对其进行一些处理,然后根据处理结果重定向到相对页面,我将url和status返回到再次使用jQuery,并使用jQuery重定向到该页面。
这是我的代码:
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');
});
});
});
Run Code Online (Sandbox Code Playgroud)
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')
....
Run Code Online (Sandbox Code Playgroud)
此方法有安全性问题吗?
有没有办法编写更好的代码来使用recaptcha V3?谢谢。
小智 1
更好的步骤:
如何在 django 应用程序上实施 Google Recaptcha v3