Python下的Django極驗滑動驗證碼的使用

1.官網直接註冊帳號申請key和valuecss

www.geetest.com   極驗滑動驗證碼官網html

2.從Github: gt3-python-sdk下載.zip文件python

3.找到裏面Django的文件夾對照官網直接copyjquery

4.上代碼--基本是copy,少數需本身修改git

views.pygithub

from geetest import GeetestLib
from django.contrib import auth
from django.http import JsonResponse
from django.shortcuts import render
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")
# 請在官網申請ID使用,示例ID不可以使用
pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c"
pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4"


# 處理極驗 獲取驗證碼的視圖
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)
View Code
urls.py
from django.conf.urls import url
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
  url(r'^login/', views.login),
    # 極驗滑動驗證碼 獲取驗證碼的url
    url(r'^pc-geetest/register', views.get_geetest),
]
View Code
login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>歡迎登陸</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/mystyle.css">
</head>
<body>

<div class="container">
    <div class="row">
        <form class="form-horizontal col-md-6 col-md-offset-3 login-form">
            {% csrf_token %}
            <div class="form-group">
                <label for="username" class="col-sm-2 control-label">用戶名</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="username" name="username" placeholder="用戶名">
                </div>
            </div>
            <div class="form-group">
                <label for="password" class="col-sm-2 control-label">密碼</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" id="password" name="password" placeholder="密碼">
                </div>
            </div>
            <div class="form-group">
                <!-- 放置極驗的滑動驗證碼 -->
                <div id="popup-captcha"></div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="button" class="btn btn-default" id="login-button">登陸</button>
                    <span class="login-error"></span>
                </div>
            </div>
        </form>
    </div>
</div>

<script src="/static/jquery-3.3.1.js"></script>
<script src="/static/bootstrap/js/bootstrap.min.js"></script>
<!-- 引入封裝了failback的接口--initGeetest -->
<script src="http://static.geetest.com/static/tools/gt.js"></script>
<script>

    // 極驗 發送登陸數據的
    var handlerPopup = function (captchaObj) {
        // 成功的回調
        captchaObj.onSuccess(function () {
            var validate = captchaObj.getValidate();
            // 1. 取到用戶填寫的用戶名和密碼 -> 取input框的值
            var username = $("#username").val();
            var password = $("#password").val();
            $.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) {
                        // 有錯誤,在頁面上提示
                        $(".login-error").text(data.msg);
                    } 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
    };
    // 當input框獲取焦點時將以前的錯誤清空
    $("#username,#password").focus(function () {
        // 將以前的錯誤清空
        $(".login-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 // 表示用戶後臺檢測極驗服務器是否宕機,通常不須要關注
                // 更多配置參數請參見:http://www.geetest.com/install/sections/idx-client-sdk.html#config
            }, handlerPopup);
        }
    })


</script>
</body>
</html>
View Code
相關文章
相關標籤/搜索