阅读 63

django 项目——滑动验证码

在登录认证中接入腾讯防水墙验证码

1. 官网操作

官网: 007.qq.com

使用微信扫码登录腾讯云控制台,然后根据官方文档,把验证码集成到项目中

快速接入:007.qq.com/python-acce…

007.qq.com/web-access.…

  1. 访问地址: cloud.tencent.com/document/pr…

  2. 访问云API秘钥

  3. 访问验证码控制台: console.cloud.tencent.com/captcha

  4. 新建验证[ 新用户可以领取一个免费的验证码套餐 ]

image.png

image.png

2. 前端引入静态文件

下载 js 文件ssl.captcha.qq.com/TCaptcha.js

前端 static 文件夹中创建文件,并复制代码

index.html 添加

<head>
    <script src ="static/js/captcha.js">
    </script>
</head>	
复制代码

创建验证标签(定制接入)

image.png

在settings.js中添加配置:

export default {
  Host:"http://api.renran.cn:8000",
  TC_captcha:{
    app_id: "2086888489",
  },
}
复制代码

3. 服务端配置

把秘钥和ID保存到settings/dev.py配置文件中.

# 腾讯防水墙配置
TENCENT_CAPTCHA = {
    "GATEWAY": "https://ssl.captcha.qq.com/ticket/verify",
    "APPID": "2086888489",
    "App_Secret_Key": "0TGMvQXvBZ54r9bOWrNYEhA**",
}

复制代码

4. login.vue

操作: cloud.tencent.com/document/pr…

新增一个回调函数,以及回调内容

image.png

image.png

<template>
  <div class="sign">
    <div class="logo"><a href="/"><img src="/static/image/nav-logo.png" alt="Logo"></a></div>
    <div class="main">


      <h4 class="title">
        <div class="normal-title">
          <a class="active" href="/login">登录</a>
          <b>·</b>
          <a id="js-sign-up-btn" class="" href="/register">注册</a>
        </div>
      </h4>
      <div class="js-sign-in-container">
        <form id="new_session" action="" method="post">
          <div class="input-prepend restyle js-normal">
            <input v-model="username" placeholder="手机号或邮箱" type="text" name="session[email_or_mobile_number]"
                   id="session_email_or_mobile_number">
            <i class="iconfont ic-user"></i>
          </div>
          <!-- 海外登录登录名输入框 -->

          <div class="input-prepend">
            <input v-model="password" placeholder="密码" type="password" name="password" id="session_password">
            <i class="iconfont ic-password"></i>
          </div>
          <div class="remember-btn">
            <input type="checkbox" v-model="remember_me"  name="remember_me"
                   id="session_remember_me"><span>记住我</span>
          </div>
          <div class="forget-btn">
            <a class="" data-toggle="dropdown" href="">登录遇到问题?</a>
          </div>
          <button @click="show_captcha" class="sign-in-button" id="sign-in-form-submit-btn" type="button">
            <span id="sign-in-loading"></span>
            登录
          </button>
        </form>
        <!-- 更多登录方式 -->
        <div class="more-sign">
          <h6>社交帐号登录</h6>
          <ul>
            <li id="weibo-link-wrap" class="">
              <a class="weibo" id="weibo-link">
                <i class="iconfont ic-weibo"></i>
              </a>
            </li>
            <li><a id="weixin" class="weixin" target="_blank" href=""><i class="iconfont ic-wechat"></i></a>
            </li>
            <li><a id="qq" class="qq" target="_blank" href=""><i class="iconfont ic-qq_connect"></i></a></li>
          </ul>
        </div>
      </div>

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

<script>
export default {
  name: "Login",

  data(){
    return {
      username:'',
      password:'',
      remember_me:false,
    }
  },
  methods:{
    show_captcha(){
      // 客户端校验用户名或者密码是否符合格式要求


      let self = this;
      var captcha1 = new TencentCaptcha(`${this.$settings.captcha_app_id}`, function(res) {

         console.log(res);
         self.$axios.get(`${self.$settings.host}/users/check_captcha_data/`,{
           params:{
             randstr:res.randstr,
             ticket: res.ticket,
           }
         }).then((res)=>{


           self.loginHandler();

         }).catch((error)=>{

         })

      });


      captcha1.show(); // 显示验证码
    },

    loginHandler(){

      this.$axios.post(`${this.$settings.host}/users/login/`,{
        username: this.username,
        password: this.password,
      }).then((res)=>{
        console.log('res>>>>>',res);

        // 保存token
        if (this.remember_me){
          localStorage.token = res.data.token;
          localStorage.id = res.data.id;
          localStorage.username = res.data.username;
          localStorage.avatar = res.data.avatar;
          localStorage.nickname = res.data.nickname;
          // sessionStorage.clear()
          sessionStorage.removeItem('token');
          sessionStorage.removeItem('id');
          sessionStorage.removeItem('username');
          sessionStorage.removeItem('avatar');
          sessionStorage.removeItem('nickname');

        }else {
          sessionStorage.token = res.data.token;
          sessionStorage.id = res.data.id;
          sessionStorage.username = res.data.username;
          sessionStorage.avatar = res.data.avatar;
          sessionStorage.nickname = res.data.nickname;
          localStorage.removeItem('token');
          localStorage.removeItem('id');
          localStorage.removeItem('username');
          localStorage.removeItem('avatar');
          localStorage.removeItem('nickname');
        }
        // 登录成功之后跳转到首页
        // location.href = '/'
        this.$confirm('恭喜您登录成功,需要继续访问吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push('/');
          // console.log(this.$route);


        }).catch(() => {
          this.$message({
            type: 'info',
            message: '有病吗?'
          });
        });


      }).catch((error)=>{
        this.$message({
            type: 'error',
            message: '用户名或者密码有误'
          })

      })

    },
  }


}
</script>

<style scoped>
input {
  outline: none;
}

*, :after, :before {
  box-sizing: border-box;
}

.sign {
  height: 100%;
  min-height: 750px;
  text-align: center;
  font-size: 14px;
  background-color: #f1f1f1
}

.sign:before {
  content: "";
  display: inline-block;
  height: 85%;
  vertical-align: middle
}

.sign .disable, .sign .disable-gray {
  opacity: .5;
  pointer-events: none
}

.sign .disable-gray {
  background-color: #969696
}

.sign .tooltip-error {
  font-size: 14px;
  line-height: 25px;
  white-space: nowrap;
  background: none
}

.sign .tooltip-error .tooltip-inner {
  max-width: 280px;
  color: #333;
  border: 1px solid #ea6f5a;
  background-color: #fff
}

.sign .tooltip-error .tooltip-inner i {
  position: static;
  margin-right: 5px;
  font-size: 20px;
  color: #ea6f5a;
  vertical-align: middle
}

.sign .tooltip-error .tooltip-inner span {
  vertical-align: middle;
  display: inline-block;
  white-space: normal;
  max-width: 230px
}

.sign .tooltip-error.right .tooltip-arrow-border {
  border-right-color: #ea6f5a
}

.sign .tooltip-error.right .tooltip-arrow-bg {
  left: 2px;
  border-right-color: #fff
}

.sign .slide-error {
  position: relative;
  padding: 10px 0;
  border: 1px solid #c8c8c8;
  border-radius: 4px
}

.sign .slide-error i {
  position: static !important;
  margin-right: 10px;
  color: #ea6f5a !important;
  vertical-align: middle
}

.sign .slide-error span {
  font-size: 15px;
  vertical-align: middle
}

.sign .slide-error div {
  margin-top: 10px;
  font-size: 13px
}

.sign .slide-error a {
  color: #3194d0
}

.sign .js-sign-up-forbidden {
  color: #999;
  padding: 80px 0 100px
}

.sign .js-sign-up-container .slide-error {
  border-bottom: none;
  border-radius: 0
}

.sign .logo {
  position: absolute;
  top: 56px;
  margin-left: 50px
}

.sign .logo img {
  width: 100px
}

.sign .main {
  width: 400px;
  margin: 60px auto 0;
  padding: 50px 50px 30px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 0 8px rgba(0, 0, 0, .1);
  vertical-align: middle;
  display: inline-block
}

.sign .reset-title, .sign .title {
  margin: 0 auto 50px;
  padding: 10px;
  font-weight: 400;
  color: #969696
}

.sign .reset-title a, .sign .title a {
  padding: 10px;
  color: #969696
}

.sign .reset-title a:hover, .sign .title a:hover {
  border-bottom: 2px solid #ea6f5a
}

.sign .reset-title .active, .sign .title .active {
  font-weight: 700;
  color: #ea6f5a;
  border-bottom: 2px solid #ea6f5a
}

.sign .reset-title b, .sign .title b {
  padding: 10px
}

.sign .reset-title {
  color: #333;
  font-weight: 700
}

.sign form {
  margin-bottom: 30px
}

.sign form .input-prepend {
  position: relative;
  width: 100%
}

.sign form .input-prepend input {
  width: 100%;
  height: 50px;
  margin-bottom: 0;
  padding: 4px 12px 4px 35px;
  border: 1px solid #c8c8c8;
  border-radius: 0 0 4px 4px;
  background-color: hsla(0, 0%, 71%, .1);
  vertical-align: middle
}

.sign form .input-prepend i {
  position: absolute;
  top: 14px;
  left: 10px;
  font-size: 18px;
  color: #969696
}

.sign form .input-prepend span {
  color: #333
}

.sign form .input-prepend .ic-show {
  top: 18px;
  left: auto;
  right: 8px;
  font-size: 12px
}

.sign form .geetest-placeholder {
  height: 44px;
  border-radius: 4px;
  background-color: hsla(0, 0%, 71%, .1);
  text-align: center;
  line-height: 44px;
  font-size: 14px;
  color: #999
}

.sign form .restyle {
  margin-bottom: 0
}

.sign form .restyle input {
  border-bottom: none;
  border-radius: 4px 4px 0 0
}

.sign form .no-radius input {
  border-radius: 0
}

.sign form .slide-security-placeholder {
  height: 32px;
  background-color: hsla(0, 0%, 71%, .1);
  border-radius: 4px
}

.sign form .slide-security-placeholder p {
  padding-top: 7px;
  color: #999;
  margin-right: -7px
}

.sign .overseas-btn {
  font-size: 14px;
  color: #999
}

.sign .overseas-btn:hover {
  color: #2f2f2f
}

.sign .remember-btn {
  float: left;
  margin: 15px 0
}

.sign .remember-btn span {
  margin-left: 5px;
  font-size: 15px;
  color: #969696;
  vertical-align: middle
}

.sign .forget-btn {
  float: right;
  position: relative;
  margin: 15px 0;
  font-size: 14px
}

.sign .forget-btn a {
  color: #999
}

.sign .forget-btn a:hover {
  color: #333
}

.sign .forget-btn .dropdown-menu {
  top: 20px;
  left: auto;
  right: 0;
  border-radius: 4px
}

.sign .forget-btn .dropdown-menu a {
  padding: 10px 20px;
  color: #333
}

.sign #sign-in-loading {
  position: relative;
  width: 20px;
  height: 20px;
  vertical-align: middle;
  margin-top: -4px;
  margin-right: 2px;
  display: none
}

.sign #sign-in-loading:after {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: transparent
}

.sign #sign-in-loading:before {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 20px;
  height: 20px;
  margin: -10px 0 0 -10px;
  border-radius: 10px;
  border: 2px solid #fff;
  border-bottom-color: transparent;
  vertical-align: middle;
  -webkit-animation: rolling .8s infinite linear;
  animation: rolling .8s infinite linear;
  z-index: 1
}

.sign .sign-in-button, .sign .sign-up-button {
  margin-top: 20px;
  width: 100%;
  padding: 9px 18px;
  font-size: 18px;
  border: none;
  border-radius: 25px;
  color: #fff;
  background: #42c02e;
  cursor: pointer;
  outline: none;
  display: block;
  clear: both
}

.sign .sign-in-button:hover, .sign .sign-up-button:hover {
  background: #3db922
}

.sign .sign-in-button {
  background: #3194d0
}

.sign .sign-in-button:hover {
  background: #187cb7
}

.sign .btn-in-resend, .sign .btn-up-resend {
  position: absolute;
  top: 7px;
  right: 7px;
  width: 100px;
  height: 36px;
  font-size: 13px;
  color: #fff;
  background-color: #42c02e;
  border-radius: 20px;
  line-height: 36px
}

.sign .btn-in-resend {
  background-color: #3194d0
}

.sign .sign-up-msg {
  margin: 10px 0;
  padding: 0;
  text-align: center;
  font-size: 12px;
  line-height: 20px;
  color: #969696
}

.sign .sign-up-msg a, .sign .sign-up-msg a:hover {
  color: #3194d0
}

.sign .overseas input {
  padding-left: 110px !important
}

.sign .overseas .overseas-number {
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 50px;
  font-size: 18px;
  color: #969696;
  border-right: 1px solid #c8c8c8
}

.sign .overseas .overseas-number span {
  margin-top: 17px;
  padding-left: 35px;
  text-align: left;
  font-size: 14px;
  display: block
}

.sign .overseas .dropdown-menu {
  width: 100%;
  max-height: 285px;
  font-size: 14px;
  border-radius: 0 0 4px 4px;
  overflow-y: auto
}

.sign .overseas .dropdown-menu li .nation-code {
  width: 65px;
  display: inline-block
}

.sign .overseas .dropdown-menu li a {
  padding: 6px 20px;
  font-size: 14px;
  line-height: 20px
}

.sign .overseas .dropdown-menu li a::hover {
  color: #fff;
  background-color: #f5f5f5
}

.sign .more-sign {
  margin-top: 50px
}

.sign .more-sign h6 {
  position: relative;
  margin: 0 0 10px;
  font-size: 12px;
  color: #b5b5b5
}

.sign .more-sign h6:before {
  left: 30px
}

.sign .more-sign h6:after, .sign .more-sign h6:before {
  content: "";
  border-top: 1px solid #b5b5b5;
  display: block;
  position: absolute;
  width: 60px;
  top: 5px
}

.sign .more-sign h6:after {
  right: 30px
}

.sign .more-sign ul {
  margin-bottom: 10px;
  list-style: none
}

.sign .more-sign ul li {
  margin: 0 5px;
  display: inline-block
}

.sign .more-sign ul a {
  width: 50px;
  height: 50px;
  line-height: 50px;
  display: block
}

.sign .more-sign ul i {
  font-size: 28px
}

.sign .more-sign .ic-weibo {
  color: #e05244
}

.sign .more-sign .ic-wechat {
  color: #00bb29
}

.sign .more-sign .ic-qq_connect {
  color: #498ad5
}

.sign .more-sign .ic-douban {
  color: #00820f
}

.sign .more-sign .ic-more {
  color: #999
}

.sign .more-sign .weibo-loading {
  pointer-events: none;
  cursor: pointer;
  position: relative
}

.sign .more-sign .weibo-loading:after {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #fff
}

body.reader-night-mode .sign .more-sign .weibo-loading:after {
  background-color: #3f3f3f
}

.sign .more-sign .weibo-loading:before {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 20px;
  height: 20px;
  margin: -10px 0 0 -10px;
  border-radius: 10px;
  border: 2px solid #e05244;
  border-bottom-color: transparent;
  vertical-align: middle;
  -webkit-animation: rolling .8s infinite linear;
  animation: rolling .8s infinite linear;
  z-index: 1
}

@keyframes rolling {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg)
  }

  to {
    -webkit-transform: rotate(1turn);
    transform: rotate(1turn)
  }
}

@-webkit-keyframes rolling {
  0% {
    -webkit-transform: rotate(0deg)
  }

  to {
    -webkit-transform: rotate(1turn)
  }
}

.sign .reset-password-input {
  border-radius: 4px !important
}

.sign .return {
  margin-left: -8px;
  color: #969696
}

.sign .return:hover {
  color: #333
}

.sign .return i {
  margin-right: 5px
}

.sign .icheckbox_square-green {
  display: inline-block;
  *display: inline;
  vertical-align: middle;
  margin: 0;
  padding: 0;
  width: 18px;
  height: 18px;
  background: url(/static/image/green.png) no-repeat;
  border: none;
  cursor: pointer;
  background-position: 0 0
}

.sign .icheckbox_square-green.hover {
  background-position: -20px 0
}

.sign .icheckbox_square-green.checked {
  background-position: -40px 0
}

.sign .icheckbox_square-green.disabled {
  background-position: -60px 0;
  cursor: default
}

.sign .icheckbox_square-green.checked.disabled {
  background-position: -80px 0
}


.geetest_panel_box > * {
  box-sizing: content-box
}

@media (max-width: 768px) {
  body {
    min-width: 0
  }

  .sign {
    height: auto;
    min-height: 0;
    background-color: transparent
  }

  .sign .logo {
    display: none
  }

  .sign .main {
    position: absolute;
    left: 50%;
    margin: 0 0 0 -200px;
    box-shadow: none
  }
}
</style>

复制代码

6. api服务端接入验证码

的文档说明: 007.qq.com/python-acce…

服务端接受验证结果并返回,

user.views代码:

# Create your views here.
from rest_framework.views import APIView
from django.conf import settings
import json
from urllib.parse import urlencode
from urllib.request import urlopen
from rest_framework.response import Response
from rest_framework import status

class CaptchaAPIView(APIView):
    def get(self,request):
        """验证码的验证结果校验"""
        AppSecretKey = settings.TENCENT_CAPTCHA["App_Secret_Key"]
        appid = settings.TENCENT_CAPTCHA["APPID"]
        Ticket = request.query_params.get("ticket")
        Randstr = request.query_params.get("randstr")
        UserIP = request._request.META.get("REMOTE_ADDR")
        print("用户ID地址:%s" % UserIP)
        params = {
            "aid": appid,
            "AppSecretKey": AppSecretKey,
            "Ticket": Ticket,
            "Randstr": Randstr,
            "UserIP": UserIP
        }
        params = urlencode(params)

        f = urlopen("%s?%s" % (settings.TENCENT_CAPTCHA["GATEWAY"], params))
        content = f.read()
        res = json.loads(content)
        print(res)
        if res:
            error_code = res["response"]
            if int(error_code) == 1:
                return Response("验证通过!")
            else:
                return Response("验证失败!%s" % res["err_msg"], status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response("验证失败!", status=status.HTTP_400_BAD_REQUEST)
复制代码

其他数据的来源

image.png

dev.py

CAPTCHA_INFO = {
    'check_url': 'https://ssl.captcha.qq.com/ticket/verify',
    'appId': '2029414629',
    'AppSecretKey': '0NmUgiKIZeki4b932NYeGQg**',

}

复制代码

路由,代码:

# 子应用路由:
from django.urls import path
from . import views
urlpatterns = [
    path("captcha/", views.CaptchaAPIView.as_view()),
]
复制代码
文章分类
前端
文章标签