1. 程式人生 > >【Django】使用geetest實現滑動驗證

【Django】使用geetest實現滑動驗證

需匯入模組social-auth-app-djangogeetest 提前去官網下載gt.js或者引入http://static.geetest.com/static/tools/gt.js


效果圖:


html:

<div class="container">
        <form action="">
            <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">登入</p>
                            <p>請在下面的輸入框中輸入您的使用者名稱和密碼</p>
                        </div>
                        <div class="panel-body">
                            <form>
                                {% csrf_token %}
                                <div class="form-group">
                                    <input type="text" class="form-control input-lg" name="user" placeholder="使用者名稱">
                                </div>
                                <div class="form-group">
                                    <input type="password" class="form-control input-lg" name="pwd" placeholder="密碼">
                                </div>
                                <div class="form-group popup-div">
                                    <!-- 放置極驗的滑動驗證碼 -->
                                    <div id="popup-captcha"></div>
                                    <span id="error"></span>
                                </div>
                                <div class="form-group">
                                    <button class="btn btn-block btn-primary btn-lg" id="login-button">登入</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </form>

    </div>

<!-- geetest -->
{#    <script src="http://static.geetest.com/static/tools/gt.js"></script>#}
    <script src="/static/js/gt.js"></script>
    <script src="/static/js/login.js"></script>

js:

// 極驗 傳送登入資料的
var handlerPopup = function (captchaObj) {
    // 成功的回撥
    captchaObj.onSuccess(function () {
        var validate = captchaObj.getValidate();
        // 1. 取到使用者填寫的使用者名稱和密碼 -> 取input框的值
        var username = $('input[name="user"]').val();
        var password = $('input[name="pwd"]').val();

        console.log(username, password);

        $.ajax({
            url: "/login/", // 進行二次驗證
            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) {
                console.log(data);
                if (data.status) {
                    // 有錯誤,在頁面上提示
                    $('#error').text(data.msg)
                } else {
                    // 登陸成功
                    location.href = data.msg;
                }
            }
        });
    });

    $("#login-button").click(function () {
        captchaObj.show();
    });
    // 將驗證碼加到id為captcha的元素裡
    captchaObj.appendTo("#popup-captcha");
};

// 當input框獲取焦點時將之前的錯誤清空
$('input[name=\"user\"]', 'input[name="pwd"]').focus(function () {
    // 將之前的錯誤清空
    $('#error').text('');
});

// 驗證開始需要向網站主後臺獲取id,challenge,success(是否啟用failback)
$.ajax({
    url: "/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, // 表示使用者後臺檢測極驗伺服器是否宕機,一般不需要關注
            width: '100%',  // 寬度
          
        }, handlerPopup);
    }
});

views:

from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.contrib import auth

from geetest import GeetestLib

def login(request):
    if request.method == "POST":
        # 初始化一個給AJAX返回的資料
        ret = {
            'status': 0,
            'msg': ''}
        # 從提交過來的資料中 取到使用者名稱和密碼
        username = request.POST.get("username")
        pwd = 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=pwd)
            if user:
                # 使用者名稱密碼正確
                # 給使用者做登入
                auth.login(request, user)  # 將登入使用者賦值給 request.user
                ret["msg"] = "/index/"
            else:
                # 使用者名稱密碼錯誤
                ret["status"] = 1
                ret["msg"] = "使用者名稱或密碼錯誤!"
        else:
            ret["status"] = 1
            ret["msg"] = "驗證碼錯誤"

        return JsonResponse(ret)

    return render(request, "login.html")