Django中使用geetest實現滑動驗證


下載第三方模塊

導入模塊social-auth-app-django 和geetest 提前去官網下載gt.js或者引入http://static.geetest.com/static/tools/gt.js

pip install social-auth-app-django
pip install geetest

在django引用

1.目錄結構

 

2.html層

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
    <style>
        .error{
    color: red;
    }
    </style>
</head>
<body>
<h3>登錄</h3>


<!-- 為使用方便,直接使用jquery.js庫,如您代碼中不需要,可以去掉 -->
<script type="text/javascript" src="/static/bootstrap/js/jquery-3.3.1.js"></script>
<script type="text/javascript" src="/static/bootstrap/js/bootstrap.js"></script>
<!-- 引入封裝了failback的接口--initGeetest -->
<script src="http://static.geetest.com/static/tools/gt.js"></script>

 <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <div class="panel panel-default login">
                    <div class="panel-heading">
                        <p class="h3">登錄&nbsp;&nbsp;博客賬號</p>
                        <p>請在下面的輸入框中輸入您的用戶名和密碼</p>
                    </div>
                    <div class="panel-body">
                        <div>
                            {% csrf_token %}
                            <div class="form-group">
                                <input type="text" class="form-control input-lg" id="user" placeholder="用戶名">
                            </div>
                            <div class="form-group">
                                <input type="password" class="form-control input-lg" id="pwd" placeholder="密碼">
                            </div>
                            <div class="form-group popup-div">
                                <!-- 放置極驗的滑動驗證碼 -->
                                <div id="popup-captcha"></div>

                            </div>
                            <div class="form-group">
                                <button class="btn btn-block btn-primary btn-lg" id="login-button" >登錄</button>
                            </div>

                            <span id="error" class="pull-right"></span>
                        </div>


                    </div>
                </div>
            </div>
        </div>


    </div>



<script>
    //發送數據
    var handlerPopup = function (captchaObj) {
    // 成功的回調
    captchaObj.onSuccess(function () {
        var validate = captchaObj.getValidate();
        var username = $("#user").val();
        var password = $("#pwd").val();
        $.ajax({
            url: "/blog/geelogin/", // 進行二次驗證
            type: "post",
            dataType: "json",
            data: {
                username: username,
                password: password,
                csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
                geetest_challenge: validate.geetest_challenge,
                geetest_validate: validate.geetest_validate,
                geetest_seccode: validate.geetest_seccode
            },
            success: function (data) {
                if(data.status){

                    $('#error').text(data.msg).css({'margin-left':'10px','color':'red'})
                }else{
                    location.href = data.msg;
                }
            }
        });
    });

    //綁定事件顯示滑動驗證碼
    $("#login-button").click(function () {
        captchaObj.show();
    });
    // 將驗證碼加到id為captcha的元素里
    captchaObj.appendTo("#popup-captcha");
    // 更多接口參考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
    // 驗證開始需要向網站主后台獲取id,challenge,success(是否啟用failback)
    $.ajax({
        url: "/blog/pc-geetest/register?t=" + (new Date()).getTime(), // 加隨機數防止緩存
        type: "get",
        dataType: "json",
        success: function (data) {
            // 使用initGeetest接口
            // 參數1:配置參數
            // 參數2:回調,回調的第一個參數驗證碼對象,之后可以使用它做appendTo之類的事件
            initGeetest({
                gt: data.gt,
                challenge: data.challenge,
                product: "popup", // 產品形式,包括:float,embed,popup。注意只對PC版驗證碼有效
                offline: !data.success // 表示用戶后台檢測極驗服務器是否宕機,一般不需要關注
                // 更多配置參數請參見:http://www.geetest.com/install/sections/idx-client-sdk.html#config
            }, handlerPopup);
        }
    });


</script>
</body>
</html>

3.urls.py

from django.contrib import admin
from django.urls import path
from django.urls import re_path,include

from blog import views

urlpatterns = [
    # path('admin/', admin.site.urls),
    # re_path(r"blog/", include(('blog.urls', 'blog'))),  # 分發
    path('login/',views.login),
    path('get_valid_img/',views.get_validCode_img),
    path('index/',views.index),
    path('geeindex/', views.geeindex),
    re_path(r"^pc-geetest/register",views.get_geetest),
    # re_path(r'^pc-geetest/validate$',views.pcvalidate),
    # re_path(r'^pc-geetest/ajax_validate', views.pcajax_validate),
    path('geelogin/',views.geelogin),

]

4.views.py

from django.shortcuts import render,HttpResponse

# Create your views here.
from django.http import JsonResponse
from django.contrib import auth

pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c"
pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4"


def geelogin(request):
    """
    登錄
    :param request:
    :return:
    """
    if request.method == 'POST':
        ret = {
            'status': None,
            'msg': '',
        }

        username = request.POST.get("username")
        password = request.POST.get("password")

        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        challenge = request.POST.get(gt.FN_CHALLENGE, '')
        validate = request.POST.get(gt.FN_VALIDATE, '')
        seccode = request.POST.get(gt.FN_SECCODE, '')
        status = request.session[gt.GT_STATUS_SESSION_KEY]
        user_id = request.session["user_id"]

        if status:
            result = gt.success_validate(challenge, validate, seccode, user_id)
        else:
            result = gt.failback_validate(challenge, validate, seccode)

        if result:
            # 驗證碼正確

            # 利用auth模塊做用戶名和密碼的校驗
            user = auth.authenticate(username=username, password=password)
            if user:
                # 用戶名密碼正確
                # 給用戶做登錄
                auth.login(request, user)  # 將登錄用戶賦值給 request.user
                ret["msg"] = "/blog/index/"
            else:
                # 用戶名密碼錯誤
                ret["status"] = 1
                ret["msg"] = "用戶名或密碼錯誤!"
        else:
            ret["status"] = 1
            ret["msg"] = "驗證碼錯誤"

        return JsonResponse(ret)

    else:
        return render(request,'geelogin.html')

def index(request):
    return render(request, 'index.html')


from geetest import GeetestLib


# 處理極驗 獲取驗證碼的視圖
def get_geetest(request):
    user_id = 'test'
    gt = GeetestLib(pc_geetest_id, pc_geetest_key)
    status = gt.pre_process(user_id)
    request.session[gt.GT_STATUS_SESSION_KEY] = status
    request.session["user_id"] = user_id
    response_str = gt.get_response_str()
    return HttpResponse(response_str)

 

5.index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<h3>首頁{{ request.user }}</h3>
</body>
</html>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM