路飞学成登录

用户的登陆认证

前端首页实现登陆状态的判断

Header.vue组件代码:

<script>
  export default {
    name: "Header",
    data(){
      return {
        // 设置一个登录标识,表示是否登录
        token: sessionStorage.token || localStorage.token,
        user_name: sessionStorage.user_name || localStorage.user_name,
        user_id: sessionStorage.user_id || localStorage.user_id,
        nav_list:[],
      };
    },
    。。。
  }
</script>

 

头部组件中实现退出登录

实现的思路:头部子组件是通过token值进行判断登录状态,所以当用户点击"退出登录",则需要移出token的值,并使用elementUI里面的弹窗组件进行提示。

Header.vue组件代码:

<template>
  <div class="header">
    <el-container>
      <el-header>
        <el-row>
          <el-col class="logo" :span="3">
            <a href="/">
              <img src="@/assets/head-logo.svg" alt="">
            </a>
          </el-col>
          <el-col class="nav" :span="16">
              <el-row>
                <el-col v-for="nav in nav_list" :span="3"><a :class="check(nav.link)?'current':''" :href="nav.link">{{nav.name}}</a></el-col>
              </el-row>
          </el-col>
          <el-col class="login-bar" :span="5">
            <el-row v-if="token">
              <el-col class="cart-ico" :span="9">
                <router-link to="">
                  <b class="goods-number">0</b>
                  <img class="cart-icon" src="@/assets/cart.svg" alt="">
                  <span><router-link to="/cart">购物车</router-link></span>
                </router-link>
              </el-col>
              <el-col class="study" :span="8" :offset="2"><router-link to="">学习中心</router-link></el-col>
              <el-col class="member" :span="5">
                <el-menu class="el-menu-demo" mode="horizontal">
                  <el-submenu index="2">
                    <template slot="title"><router-link to=""><img src="@/assets/logo@2x.png" alt=""></router-link></template>
                    <el-menu-item index="2-1">我的账户</el-menu-item>
                    <el-menu-item index="2-2">我的订单</el-menu-item>
                    <el-menu-item index="2-3">我的优惠卷</el-menu-item>
                    <el-menu-item index="2-3"><span @click="logout">退出登录</span></el-menu-item>
                  </el-submenu>
                </el-menu>
              </el-col>
            </el-row>
            <el-row v-else>
              <el-col class="cart-ico" :span="9">
                <router-link to="">
                  <img class="cart-icon" src="@/assets/cart.svg" alt="">
                  <span><router-link to="/cart">购物车</router-link></span>
                </router-link>
              </el-col>
              <el-col :span="10" :offset="5">
                <span class="register">
                  <router-link to="/login">登录</router-link>
                  &nbsp;&nbsp;|&nbsp;&nbsp;
                  <router-link to="/register">注册</router-link>
                </span>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-header>
    </el-container>
  </div>
</template>
​
<script>
  export default {
    name: "Header",
    data(){
      return {
        // 设置一个登录标识,表示是否登录
        token: sessionStorage.token || localStorage.token,
        user_name: sessionStorage.user_name || localStorage.user_name,
        user_id: sessionStorage.user_id || localStorage.user_id,
        nav_list:[],
      };
    },
    created() {
      // 获取导航
      this.$axios.get(this.$settings.Host+"/nav/").then(response=>{
        this.nav_list = response.data
        console.log(this.nav_list)
      }).catch(error=>{
        console.log(error.response)
      })
    },
    methods:{
      check(link){
        return link==window.location.pathname
      },
      logout(){
​
        this.token = false;
        this.user_id=false;
        this.user_name=false;
​
        sessionStorage.removeItem("token");
        sessionStorage.removeItem("user_id");
        sessionStorage.removeItem("user_name");
​
        localStorage.removeItem("token");
        localStorage.removeItem("user_id");
        localStorage.removeItem("user_name");
​
        this.$alert('退出登录成功!', '路飞学城', {
          confirmButtonText: '确定'
        });
      }
    }
  }
</script>

 

 

在登录认证中接入极验验证

官网: https://www.geetest.com/first_page/

注册登录以后,即进入登录后台,选择行为验证。

 

 

 

接下来,就可以根据官方文档,把验证码集成到项目中了

 

''文档地址:https://docs.geetest.com/install/overview/start/

下载和安装验证码模块包。

git clone https://github.com/GeeTeam/gt3-python-sdk.git

安装依赖模块

pip install requests

 

把验证码模块放置到在libs目录中

users/views.py文件下方:

from rest_framework.views import APIView
from luffy.libs.geetest import GeetestLib
from django.conf import settings
import random
from rest_framework.response import Response
​
class CaptchaAPIView(APIView):
    """极验验证码"""
    def get(self,request):
        """提供生成验证码的配置信息"""
        user_id = '%06d' % random.randint(1,9999)
        gt = GeetestLib(settings.PC_GEETEST_ID, settings.PC_GEETEST_KEY)
        status = gt.pre_process(user_id)
        print(status)
​
        # 把这两段数据不要保存在session里面, 保存到redis里面
        request.session[gt.GT_STATUS_SESSION_KEY] = status
        request.session["user_id"] = user_id
​
        response_str = gt.get_response_str()
        return Response(response_str)
​
    def post(self,request):
        """进行二次验证"""
        pass

users/urls.py路由注册:

path(r'captcha/', views.CaptchaAPIView.as_view() ),

配置文件settings/dev.py代码:

PC_GEETEST_ID = '5f4ab1914455506edffaffd4da37fea5'
PC_GEETEST_KEY ='460e13a49d687e5e44e25c383f0473a6'

 

前端获取显示并校验验证码

把下载会哦图的验证码模块包中的gt.js放置到前端项目中,并在main.js中引入

// 导入gt极验
import '../static/globals/gt.js'

显示验证码

<template>
    <div class="login-box">
        <img src="../../static/img/Loginbg.3377d0c.jpg" alt="">
        <div class="login">
            <div class="login-title">
                <img src="../../static/img/Logotitle.1ba5466.png" alt="">
                <p>帮助有志向的年轻人通过努力学习获得体面的工作和生活!</p>
            </div>
            <div class="login_box">
                <div class="title">
                    <span @click="login_type=0">密码登录</span>
                    <span @click="login_type=1">短信登录</span>
                </div>
                <div class="inp" v-if="login_type==0">
                    <input v-model = "username" type="text" placeholder="用户名 / 手机号码" class="user">
                    <input v-model = "password" type="password" name="" class="pwd" placeholder="密码">
                    <div id="geetest1"></div>
                    <div class="rember">
                        <p>
                            <input type="checkbox" class="no" v-model="remember"/>
                            <span>记住密码</span>
                        </p>
                        <p>忘记密码</p>
                    </div>
                    <button class="login_btn" @click="loginhander">登录</button>
                    <p class="go_login" >没有账号 <router-link to="/reg">立即注册</router-link></p>
                </div>
                <div class="inp" v-show="login_type==1">
                    <input v-model = "username" type="text" placeholder="手机号码" class="user">
                    <input v-model = "password"  type="text" class="pwd" placeholder="短信验证码">
          <button id="get_code">获取验证码</button>
                    <button class="login_btn">登录</button>
                    <p class="go_login" >没有账号 <router-link to="/reg">立即注册</router-link></p>
                </div>
            </div>
        </div>
    </div>
</template>
​
<script>
export default {
  name: 'Login',
  data(){
    return {
        login_type: 0,
        username:"",
        password:"",
        remember:"",
    }
  },
  mounted(){
    // 请求后端获取生成验证码的流水号
    this.$axios.get(this.$settings.Host + "/users/captcha/",{
      responseType: 'json', // 希望返回json数据
    }).then(response => {
      let data = response.data;
​
      // 验证初始化配置
      initGeetest({
        gt: data.gt,
        challenge: data.challenge,
        product: "popup", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
        offline: !data.success
      },this.handlerPopup)
    }).catch(error => {
      console.log(error.response);
    });
  },
  methods:{
    // 用户登录
    loginhander(){
      。。。。
    },
    // 验证码的成功验证事件方法
    handlerPopup(captchaObj){
       // 把验证码添加到模板中制定的页面
       captchaObj.appendTo("#geetest1");
      
    },
  },
​
};
</script>

效果:

后端提供二次验证的API接口

from django.shortcuts import render
​
# Create your views here.
from .serializers import UserModelSerializer
from rest_framework.generics import CreateAPIView
from .models import User
class UserAPIView(CreateAPIView):
    serializer_class = UserModelSerializer
    queryset = User.objects.all()
​
​
from rest_framework.views import APIView
from luffy.libs.geetest import GeetestLib
from django.conf import settings
import random
from rest_framework.response import Response
​
class CaptchaAPIView(APIView):
    """极验验证码"""
    gt = GeetestLib(settings.PC_GEETEST_ID, settings.PC_GEETEST_KEY)
    def get(self,request):
        """提供生成验证码的配置信息"""
        user_id = '%06d' % random.randint(1,9999)
        status = self.gt.pre_process(user_id)
        print(status)
​
        # 把这两段数据不要保存在session里面, 保存到redis里面
        request.session[self.gt.GT_STATUS_SESSION_KEY] = status
        request.session["user_id"] = user_id
​
        response_str = self.gt.get_response_str()
        return Response(response_str)
​
    def post(self,request):
        """进行二次验证"""
        challenge = request.data.get(self.gt.FN_CHALLENGE, '')
        validate = request.data.get(self.gt.FN_VALIDATE, '')
        seccode = request.data.get(self.gt.FN_SECCODE, '')
​
        status = request.session.get(self.gt.GT_STATUS_SESSION_KEY)
        user_id = request.session.get("user_id")
​
        if status:
            result = self.gt.success_validate(challenge, validate, seccode, user_id)
        else:
            result = self.gt.failback_validate(challenge, validate, seccode)
​
        # 返回一个随机字符串,在用户登录提供数据时一并发送到后端,进行验证
        # 后面可以使用redis保存
    
​
        return Response({"message":result})

 

Login.vue代码

<template>
    <div class="login-box">
        <img src="../../static/img/Loginbg.3377d0c.jpg" alt="">
        <div class="login">
            <div class="login-title">
                <img src="../../static/img/Logotitle.1ba5466.png" alt="">
                <p>帮助有志向的年轻人通过努力学习获得体面的工作和生活!</p>
            </div>
            <div class="login_box">
                <div class="title">
                    <span @click="login_type=0">密码登录</span>
                    <span @click="login_type=1">短信登录</span>
                </div>
                <div class="inp" v-if="login_type==0">
                    <input v-model = "username" type="text" placeholder="用户名 / 手机号码" class="user">
                    <input v-model = "password" type="password" name="" class="pwd" placeholder="密码">
                    <div id="geetest1"></div>
                    <div class="rember">
                        <p>
                            <input type="checkbox" class="no" v-model="remember"/>
                            <span>记住密码</span>
                        </p>
                        <p>忘记密码</p>
                    </div>
                    <button class="login_btn" @click="loginhander">登录</button>
                    <p class="go_login" >没有账号 <router-link to="/reg">立即注册</router-link></p>
                </div>
                <div class="inp" v-show="login_type==1">
                    <input v-model = "username" type="text" placeholder="手机号码" class="user">
                    <input v-model = "password"  type="text" class="pwd" placeholder="短信验证码">
          <button id="get_code">获取验证码</button>
                    <button class="login_btn">登录</button>
                    <p class="go_login" >没有账号 <router-link to="/reg">立即注册</router-link></p>
                </div>
            </div>
        </div>
    </div>
</template>
​
<script>
export default {
  name: 'Login',
  data(){
    return {
        login_type: 0,
        username:"",
        password:"",
        remember:"",
        is_geek:false,
    }
  },
  mounted(){
    // 请求后端获取生成验证码的流水号
    this.$axios.get(this.$settings.Host + "/users/captcha/",{
      responseType: 'json', // 希望返回json数据
    }).then(response => {
      let data = response.data;
​
      // 验证初始化配置
      initGeetest({
        gt: data.gt,
        challenge: data.challenge,
        product: "popup", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
        offline: !data.success
      },this.handlerPopup)
    }).catch(error => {
      console.log(error.response);
    });
  },
  methods:{
    // 用户登录
    loginhander(){
      // 判断用户是否已经通过了极验验证
      if(!this.is_geek){
        return false;
      }
​
      this.$axios.post(this.$settings.Host+"/users/login/",{
        username:this.username,
        password:this.password,
      }).then(response=>{
        let data = response.data
        // 根据用户是否勾选了记住密码来保存用户认证信息
        if(this.remember){
          // 记住密码
          localStorage.token = data.token;
          localStorage.user_id = data.id;
          localStorage.user_name = data.username;
​
        }else{
          // 不需要记住密码
          sessionStorage.token = data.token;
          sessionStorage.user_id = data.id;
          sessionStorage.user_name = data.username;
        }
​
        // 登录成功以后,跳转会上一个页面
        this.$router.go(-1);
​
      }).catch(error=>{
        console.log(error.response)
      })
    },
    // 验证码的成功验证事件方法
    handlerPopup(captchaObj){
       // 把验证码添加到模板中制定的页面
       captchaObj.appendTo("#geetest1");
​
       // 记录vue对象
       let _this = this;
​
       // 监听用户对于验证码的操作是否成功了
       captchaObj.onSuccess(()=>{
          var validate = captchaObj.getValidate();
​
          _this.$axios.post(_this.$settings.Host+"/users/captcha/",{
              geetest_challenge: validate.geetest_challenge,
              geetest_validate: validate.geetest_validate,
              geetest_seccode: validate.geetest_seccode
          }).then(response=>{
              // 在用户成功添加数据以后,可以允许点击登录按钮
              _this.is_geek = true;
​
          }).catch(error=>{
              console.log(error.response)
          })
​
        });
​
    },
  },
​
};
</script>
<style scoped>
.login-box{
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
    margin-top: -80px;
}
.login-box img{
    width: 100%;
    min-height: 100%;
}
.login-box .login {
    position: absolute;
    width: 500px;
    height: 400px;
    left: 0;
    margin: auto;
    right: 0;
    bottom: 0;
    top: -220px;
}
.login .login-title{
     width: 100%;
    text-align: center;
}
.login-title img{
    width: 190px;
    height: auto;
}
.login-title p{
    font-size: 18px;
    color: #fff;
    letter-spacing: .29px;
    padding-top: 10px;
    padding-bottom: 50px;
}
.login_box{
    width: 400px;
    height: auto;
    background: #fff;
    box-shadow: 0 2px 4px 0 rgba(0,0,0,.5);
    border-radius: 4px;
    margin: 0 auto;
    padding-bottom: 40px;
}
.login_box .title{
    font-size: 20px;
    color: #9b9b9b;
    letter-spacing: .32px;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    justify-content: space-around;
    padding: 50px 60px 0 60px;
    margin-bottom: 20px;
    cursor: pointer;
}
.login_box .title span:nth-of-type(1){
    color: #4a4a4a;
    border-bottom: 2px solid #84cc39;
}
​
.inp{
    width: 350px;
    margin: 0 auto;
}
.inp input{
    outline: 0;
    width: 100%;
    height: 45px;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    text-indent: 20px;
    font-size: 14px;
    background: #fff !important;
}
.inp input.user{
    margin-bottom: 16px;
}
.inp .rember{
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    margin-top: 10px;
}
.inp .rember p:first-of-type{
    font-size: 12px;
    color: #4a4a4a;
    letter-spacing: .19px;
    margin-left: 22px;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    /*position: relative;*/
}
.inp .rember p:nth-of-type(2){
    font-size: 14px;
    color: #9b9b9b;
    letter-spacing: .19px;
    cursor: pointer;
}
​
.inp .rember input{
    outline: 0;
    width: 30px;
    height: 45px;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    text-indent: 20px;
    font-size: 14px;
    background: #fff !important;
}
​
.inp .rember p span{
    display: inline-block;
    font-size: 12px;
    width: 100px;
  /*position: absolute;*/
/*left: 20px;*/
​
}
#geetest{
    margin-top: 20px;
}
.login_btn{
     width: 100%;
    height: 45px;
    background: #84cc39;
    border-radius: 5px;
    font-size: 16px;
    color: #fff;
    letter-spacing: .26px;
    margin-top: 30px;
}
.inp .go_login{
    text-align: center;
    font-size: 14px;
    color: #9b9b9b;
    letter-spacing: .26px;
    padding-top: 20px;
}
.inp .go_login span{
    color: #84cc39;
    cursor: pointer;
}
</style>

修改验证码框的样式位置。

static/css/reset.css,代码:

.geetest_holder{
	padding-top: 15px;
	width: 100%!important;
}

 

用户的注册认证

前端显示注册页面并调整首页头部和登陆页面的注册按钮的链接。

注册页面Register,主要是通过登录页面进行改成而成./

<template>
	<div class="box">
		<img src="https://www.luffycity.com/static/img/Loginbg.3377d0c.jpg" alt="">
		<div class="register">
			<div class="register_box">
        <div class="register-title">注册路飞学城</div>
				<div class="inp">
					<input v-model = "mobile" type="text" placeholder="手机号码" class="user">
					<div id="geetest"></div>
					<input v-model = "sms" type="text" placeholder="输入验证码" class="user">
					<button class="register_btn" >注册</button>
					<p class="go_login" >已有账号 <router-link to="/login">直接登录</router-link></p>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
export default {
  name: 'Register',
  data(){
    return {
        sms:"",
        mobile:"",
        validateResult:false,
    }
  },
  created(){
  },
  methods:{},

};
</script>

<style scoped>
.box{
	width: 100%;
  height: 100%;
	position: relative;
  overflow: hidden;
}
.box img{
	width: 100%;
  min-height: 100%;
}
.box .register {
	position: absolute;
	width: 500px;
	height: 400px;
	top: 0;
	left: 0;
  margin: auto;
  right: 0;
  bottom: 0;
  top: -338px;
}
.register .register-title{
    width: 100%;
    font-size: 24px;
    text-align: center;
    padding-top: 30px;
    padding-bottom: 30px;
    color: #4a4a4a;
    letter-spacing: .39px;
}
.register-title img{
    width: 190px;
    height: auto;
}
.register-title p{
    font-family: PingFangSC-Regular;
    font-size: 18px;
    color: #fff;
    letter-spacing: .29px;
    padding-top: 10px;
    padding-bottom: 50px;
}
.register_box{
    width: 400px;
    height: auto;
    background: #fff;
    box-shadow: 0 2px 4px 0 rgba(0,0,0,.5);
    border-radius: 4px;
    margin: 0 auto;
    padding-bottom: 40px;
}
.register_box .title{
	font-size: 20px;
	color: #9b9b9b;
	letter-spacing: .32px;
	border-bottom: 1px solid #e6e6e6;
	 display: flex;
    	justify-content: space-around;
    	padding: 50px 60px 0 60px;
    	margin-bottom: 20px;
    	cursor: pointer;
}
.register_box .title span:nth-of-type(1){
	color: #4a4a4a;
    	border-bottom: 2px solid #84cc39;
}

.inp{
	width: 350px;
	margin: 0 auto;
}
.inp input{
    border: 0;
    outline: 0;
    width: 100%;
    height: 45px;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    text-indent: 20px;
    font-size: 14px;
    background: #fff !important;
}
.inp input.user{
    margin-bottom: 16px;
}
.inp .rember{
     display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    margin-top: 10px;
}
.inp .rember p:first-of-type{
    font-size: 12px;
    color: #4a4a4a;
    letter-spacing: .19px;
    margin-left: 22px;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    /*position: relative;*/
}
.inp .rember p:nth-of-type(2){
    font-size: 14px;
    color: #9b9b9b;
    letter-spacing: .19px;
    cursor: pointer;
}

.inp .rember input{
    outline: 0;
    width: 30px;
    height: 45px;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    text-indent: 20px;
    font-size: 14px;
    background: #fff !important;
}

.inp .rember p span{
    display: inline-block;
  font-size: 12px;
  width: 100px;
  /*position: absolute;*/
/*left: 20px;*/

}
#geetest{
	margin-top: 20px;
}
.register_btn{
     width: 100%;
    height: 45px;
    background: #84cc39;
    border-radius: 5px;
    font-size: 16px;
    color: #fff;
    letter-spacing: .26px;
    margin-top: 30px;
}
.inp .go_login{
    text-align: center;
    font-size: 14px;
    color: #9b9b9b;
    letter-spacing: .26px;
    padding-top: 20px;
}
.inp .go_login span{
    color: #84cc39;
    cursor: pointer;
}
</style>

前端注册路由:

import Register from "../components/Register"

// 配置路由列表
export default new Router({
  mode:"history",
  routes:[
    // 路由列表
	...
    {
      name:"Register",
      path: "/register",
      component:Register,
    }
  ]
})

修改首页头部的连接:

# Header.vue
<span class="header-register"><router-link to="/register">注册</router-link></span>
#Login.vue
<p class="go_login" >没有账号 <router-link to="/register">立即注册</router-link></p>

 

 

注册功能的实现

接下来,我们把注册过程中一些注册信息(例如:短信验证码)和session缓存到redis数据库中。

安装django-redis。

pip install django-redis

 

在settings.py配置中添加一下代码:

# 设置redis缓存
CACHES = {
    # 默认缓存
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        # 项目上线时,需要调整这里的路径
        "LOCATION": "redis://127.0.0.1:6379/0",

        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    # 提供给xadmin或者admin的session存储
    "session": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    # 提供存储短信验证码
    "sms_code":{
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

# 设置xadmin用户登录时,登录信息session保存到redis
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "session"

关于django-redis 的使用,说明文档可见http://django-redis-chs.readthedocs.io/zh_CN/latest/

django-redis提供了get_redis_connection的方法,通过调用get_redis_connection方法传递redis的配置名称可获取到redis的连接对象,通过redis连接对象可以执行redis命令

https://redis-py.readthedocs.io/en/latest/

使用范例:

from django_redis import get_redis_connection
// 链接redis数据库
redis_conn = get_redis_connection("default")

 

 

使用云通讯发送短信

在登录后的平台上面获取一下信息:

ACCOUNT SID:8aaf0708697b6beb01699f4442911776
AUTH TOKEN : b4dea244f43a4e0f90e557f0a99c70fa
AppID(默认):8aaf0708697b6beb01699f4442e3177c
Rest URL(生产): app.cloopen.com:8883         [项目上线时使用真实短信发送服务器]
Rest URL(开发): sandboxapp.cloopen.com:8883  [项目开发时使用沙箱短信发送服务器]

找到sdkdemo进行下载

 

在开发过程中,为了节约发送短信的成本,可以把自己的或者同事的手机加入到测试号码中.

 

后端生成短信验证码

from .yuntongxun.sms import CCP
class SMSCodeAPIView(APIView):
    """
    短信验证码
    """
    def get(self, request, mobile):
        """
        短信验证码
        """
        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)

        # 保存短信验证码与发送记录
        redis_conn = get_redis_connection('verify_codes')
        # 使用redis提供的管道操作可以一次性执行多条redis命令
        pl = redis_conn.pipeline()
        pl.multi()
        pl.setex("sms_%s" % mobile, 300, sms_code) # 设置短信有效期为300s
        pl.setex("sms_time_%s" % mobile, 60, 1)    # 设置发送短信间隔为60s
        pl.execute()

        # 发送短信验证码
        ccp = CCP()
        ccp.send_template_sms(mobile, [code, "5"], 1)

        return Response({"message": "OK"}, status.HTTP_200_OK)

 

后端保存用户注册信息

创建序列化器对象[暂时不涉及到手机验证码功能]

from rest_framework import serializers
from .models import User
import re
class UserModelSerializer(serializers.ModelSerializer):
    """用户信息序列化器"""
    sms_code = serializers.CharField(label='手机验证码', required=True, allow_null=False, allow_blank=False, write_only=True)
    password2 = serializers.CharField(label='确认密码', required=True, allow_null=False, allow_blank=False, write_only=True)

    class Meta:
        model=User
        fields = ('sms_code', 'mobile', "username", 'password','password2')
        extra_kwargs={
            "password":{
                "write_only":True
            }
        }

	def validate_mobile(self, mobile):
        # 验证格式
        result = re.match('^1[3-9]\d{9}$', mobile)
        if not result:
            raise serializers.ValidationError("手机号码格式有误!")

            # 验证唯一性
            try:
                user = User.objects.get(mobile=mobile)
                if user:
                    raise serializers.ValidationError("当前手机号码已经被注册!")

                    except User.DoesNotExist:
                        pass

                    return mobile

    def validate(self,data):
        # 验证密码
        password = data.get("password")
        password2 = data.get("password2")
        if len(password)<6 or len(password) > 16:
            raise serializers.ValidationError('密码长度必须在6-16位之间~')

        if password != password2:
            raise serializers.ValidationError('密码和确认必须一致~')

        return data

    def create(self, validated_data):
        # 删除一些不需要保存到数据库里面的字段
        del validated_data['password2']
        del validated_data['sms_code']
        
        # 因为数据库中默认用户名是唯一的,所以我们把用户手机号码作为用户名
        validated_data["username"] = validated_data["mobile"]
        
        # 继续调用ModelSerializer内置的添加数据功能
        user = super().create(validated_data)

        # 针对密码要加密
        user.set_password(user.password)
        # 修改密码等用于更新了密码,所以需要保存
        user.save()

        return user

视图代码:

# users/views.py
from rest_framework.generics import CreateAPIView
from .models import User
from .serializers import UserModelSerializer
class UserAPIView(CreateAPIView):
    """用户管理"""
    queryset = User.objects.all()
    serializer_class = UserModelSerializer

 

设置路由

# 子应用路由 urls.py
urlpatterns=[
	...
    path(r"user", views.UserAPIView.as_view()),
]

 

客户端发送注册信息和发送短信

<template>
	<div class="box">
		<img src="https://www.luffycity.com/static/img/Loginbg.3377d0c.jpg" alt="">
		<div class="register">
			<div class="register_box">
        <div class="register-title">注册路飞学城</div>
				<div class="inp">
          <!--<el-select v-model="region">-->
            <!--<el-option v-for="item in region_list" :label="item.nation_name+'('+item.nation_code+')'" :value="item.nation_code"></el-option>-->
          <!--</el-select>-->
					<input v-model = "mobile" type="text" placeholder="手机号码" class="user">
					<input v-model = "password" type="password" placeholder="密码" class="user">
					<input v-model = "password2" type="password" placeholder="确认密码" class="user">
          <div id="geetest"></div>
					<div class="sms">
            <input v-model="sms_code" maxlength="16" type="text" placeholder="输入验证码" class="user">
            <span class="get_sms" @click="send_sms">{{get_sms_text}}</span>
          </div>
					<button class="register_btn" @click="registerHander">注册</button>
					<p class="go_login" >已有账号 <router-link to="/login">直接登录</router-link></p>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
export default {
  name: 'Register',
  data(){
    return {
        region:"+86",
        sms_code:"",
        password:"",
        password2:"",
        mobile:"",
        validateResult:false,
        get_sms_text:"获取验证码",
    }
  },
  created(){
    // 页面初始化的时候设置号码的地区号
    // this.region_list = this.$nation;

    // 显示图片验证码
    this.$axios.get("http://127.0.0.1:8000/users/verify").then(response=>{
          // 请求成功
          let data = response.data;
          // 使用initGeetest接口
          // 参数1:配置参数
          // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
          console.log(response.data);
          data = JSON.parse(data);
          initGeetest({
              gt: data.gt,
              challenge: data.challenge,
              width: "350px",
              product: "embed", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
              offline: !data.success // 表示用户后台检测极验服务器是否宕机,一般不需要关注
              // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
          }, this.handlerPopup);
    }).catch(error=>{
      console.log(error)
    })

  },
  methods:{
    send_sms(){
      let reg = /1[1-9]{2}\d{8}/;
      if( !reg.test(this.mobile) ){
        return false;
      }

      // 如果get_sms_text 不是文本,而是数字,则表示当前手机号码还在60秒的发送短信间隔内
      if(this.get_sms_text != "获取验证码"){
        return false;
      }

      // 发送短信
      let _this = this;
      this.$axios.get("http://127.0.0.1:8000/users/sms?mobile="+this.mobile).then(response=>{
        console.log(response);
        // 显示发送短信以后的文本倒计时
        let time = 60;
        let timer = setInterval(()=>{
          --time;
          if(time <=1){
            // 如果倒计时为0,则关闭当前定时器
             _this.get_sms_text = "获取验证码";
            clearInterval(timer);
          }else{
              _this.get_sms_text = time;
          }
        },1000)
      }).catch(error=>{
        console.log(error);
      })

    },
    registerHander(){
      // 注册信息提交
      // 提交数据前判断用户是否通过了验证码校验
      if(!this.validateResult){
          alert("验证码验证有误");
          return false;
      }
      this.$axios.post("http://127.0.0.1:8000/users/user",{
          "mobile":this.mobile,
          "password":this.password,
          "password2":this.password2,
          "sms_code":this.sms_code,
        },{
          responseType:"json",
        }).
          then(response=>{
            // 请求成功,保存登陆状态
            localStorage.removeItem("token");
            let data = response.data;
            sessionStorage.token = data.token;
            sessionStorage.id = data.id;
            sessionStorage.username = data.mobile;
            // 注册成功以后默认表示已经登录了,跳转用户中心的页面
            // this.$router.push("/user");
            alert("注册成功!");
        }).catch(error=>{
          console.log(error);
        })
      },
    handlerPopup(captchaObj){
        // 验证码成功的回调
        let _this = this;
        captchaObj.onSuccess(function () {
            var validate = captchaObj.getValidate();
            _this.$axios.post("http://127.0.0.1:8000/users/verify",{
                    geetest_challenge: validate.geetest_challenge,
                    geetest_validate: validate.geetest_validate,
                    geetest_seccode: validate.geetest_seccode
                },{
                  responseType:"json",
            }).then(response=>{
              // 请求成功
              console.log(response.data);
              if(response.data.status == "success") {
                  _this.validateResult = true;  // 获取验证结果
              }
            }).catch(error=>{
              // 请求失败
              console.log(error)
            })
        });
        // 将验证码加到id为captcha的元素里
        captchaObj.appendTo("#geetest");
      }
  },

};
</script>

<style scoped>
.box{
	width: 100%;
  height: 100%;
	position: relative;
  overflow: hidden;
}
.el-select{
  width:100%;
  margin-bottom: 15px;
}
.box img{
	width: 100%;
  min-height: 100%;
}
.box .register {
	position: absolute;
	width: 500px;
	height: 400px;
	top: 0;
	left: 0;
  margin: auto;
  right: 0;
  bottom: 0;
  top: -338px;
}
.register .register-title{
    width: 100%;
    font-size: 24px;
    text-align: center;
    padding-top: 30px;
    padding-bottom: 30px;
    color: #4a4a4a;
    letter-spacing: .39px;
}
.register-title img{
    width: 190px;
    height: auto;
}
.register-title p{
    font-family: PingFangSC-Regular;
    font-size: 18px;
    color: #fff;
    letter-spacing: .29px;
    padding-top: 10px;
    padding-bottom: 50px;
}
.sms{
  margin-top: 15px;
  position: relative;
}
.sms .get_sms{
  position: absolute;
  right: 15px;
  top: 14px;
  font-size: 14px;
  color: #ffc210;
  cursor: pointer;
  border-left: 1px solid #979797;
  padding-left: 20px;
}

.register_box{
    width: 400px;
    height: auto;
    background: #fff;
    box-shadow: 0 2px 4px 0 rgba(0,0,0,.5);
    border-radius: 4px;
    margin: 0 auto;
    padding-bottom: 40px;
}
.register_box .title{
	font-size: 20px;
	color: #9b9b9b;
	letter-spacing: .32px;
	border-bottom: 1px solid #e6e6e6;
	 display: flex;
    	justify-content: space-around;
    	padding: 50px 60px 0 60px;
    	margin-bottom: 20px;
    	cursor: pointer;
}
.register_box .title span:nth-of-type(1){
	color: #4a4a4a;
    	border-bottom: 2px solid #84cc39;
}

.inp{
	width: 350px;
	margin: 0 auto;
}
.inp input{
    border: 0;
    outline: 0;
    width: 100%;
    height: 45px;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    text-indent: 20px;
    font-size: 14px;
    background: #fff !important;
}
.inp input.user{
    margin-bottom: 16px;
}
.inp .rember{
     display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    margin-top: 10px;
}
.inp .rember p:first-of-type{
    font-size: 12px;
    color: #4a4a4a;
    letter-spacing: .19px;
    margin-left: 22px;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    /*position: relative;*/
}
.inp .rember p:nth-of-type(2){
    font-size: 14px;
    color: #9b9b9b;
    letter-spacing: .19px;
    cursor: pointer;
}

.inp .rember input{
    outline: 0;
    width: 30px;
    height: 45px;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    text-indent: 20px;
    font-size: 14px;
    background: #fff !important;
}

.inp .rember p span{
    display: inline-block;
  font-size: 12px;
  width: 100px;
  /*position: absolute;*/
/*left: 20px;*/

}
#geetest{
	margin-top: 20px;
}
.register_btn{
     width: 100%;
    height: 45px;
    background: #84cc39;
    border-radius: 5px;
    font-size: 16px;
    color: #fff;
    letter-spacing: .26px;
    margin-top: 30px;
}
.inp .go_login{
    text-align: center;
    font-size: 14px;
    color: #9b9b9b;
    letter-spacing: .26px;
    padding-top: 20px;
}
.inp .go_login span{
    color: #84cc39;
    cursor: pointer;
}
</style>

<template>
  <div class="courses">
      <Header :current_page="current_page"/>
      <div class="main">
          <div class="filter">
            <el-row class="filter-el-row1">
              <el-col :span="2" class="filter-text">课程分类:</el-col>
              <el-col :span="2" :class="filter.cate==0?'current':''"><span @click="filter.cate=0">全部</span></el-col>
              <el-col v-for="cate in cate_list" :class="filter.cate==cate.id?'current':''" :span="2"><span @click="filter.cate=cate.id">{{cate.name}}</span></el-col>
            </el-row>
            <el-row class="filter-el-row2">
              <el-col :span="2" class="filter-text filter-text2">筛&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;选:</el-col>
              <el-col :span="2" :class="filter.id?'current':''"><span @click="filter.id=true;filter.hots=false;filter.price=0">默认</span></el-col>
              <el-col :span="2" :class="filter.hots?'current':''"><span @click="filter.hots=true;filter.id=false;filter.price=0">人气</span></el-col>
              <el-col :span="2" class="">
                <span :class="filter.price!=0?'current':''">价格</span>
                <div class="filter-price">
                  <span class="up"  :class="filter.price==1?'current':''" @click="filter.price=1;filter.hots=false;filter.id=false;"><i class="el-icon-caret-top"></i></span>
                  <span class="down" :class="filter.price==2?'current':''" @click="filter.price=2;filter.hots=false;filter.id=false;"><i class="el-icon-caret-bottom"></i></span>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="courses_list">
              <el-row class="course-item" v-for="course in course_list">
                <el-col :span="24" class="course-item-box">
                  <el-row>
                    <el-col :span="12" class="course-item-left"><img :src="course.course_img" alt=""></el-col>
                    <el-col :span="12" class="course-item-right">
                        <div class="course-title">
                          <p class="box-title">{{course.name}}</p>
                          <p class="box-number">{{course.students}}人已加入学习</p>
                        </div>
                        <div class="author">
                          <p class="box-author">{{course.teacher.name}} {{course.teacher.title}}</p>
                          <p class="lession" v-if="course.pub_lessons==course.lessons">共{{course.lessons}}课时<span>/更新完成</span></p>
                          <p class="lession" v-else>共{{course.lessons}}课时<span>/已更新{{course.pub_lessons}}课时</span></p>
                        </div>
                        <el-row class="course-content">
                            <div v-for="chapters in course.coursechapters">
                            <el-col v-for="lesson in chapters.coursesections" :span="12"><i class="el-icon-caret-right"></i>01 | {{chapters.name|catcode}}-{{lesson.name|catcode}}<span v-if="lesson.free_trail" class="free">免费</span> </el-col>
                            </div>
                        </el-row>
                        <div class="course-price">
                            <p class="course-price-left">
                              <span class="discount">限时免费</span>
                              <span class="count">¥0.00</span>
                              <span class="old_count">原价: ¥{{course.price}}元</span>
                            </p>
                            <button class="buy">立即购买</button>
                        </div>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
          </div>
      </div>
      <Footer/>
  </div>
</template>

<script>
  import Header from "./common/Header"
  import Footer from "./common/Footer"
  export default {
    name:"Courses",
    data(){
      return {
        course_list_url:"", // 获取课程列表的url地址
        current_page:1,
        filter_price:false,
        cate_list: [],  // 课程分类列表
        course_list:[], // 课程列表
        filter:{
          cate: 0, // 当前用户选中的课程分类
          id:true, // true表示使用id作为排序字段
          hots: false,  // false表示不使用students学习人数作为排序字段
          price: 0, // 0表示不对价格进行排序,如果1,则对价格进行升序处理,如果2,则对价格进行降序处理
        }
      }
    },
    components:{
      Header,
      Footer,
    },
    watch:{
      "filter.cate": function(){
          this.get_course_list()
      },
      "filter.id": function(){
          this.get_course_list()
      },
      "filter.hots": function(){
          this.get_course_list()
      },
      "filter.price": function(){
          this.get_course_list()
      },
    },
    methods:{
      get_course_list(){
          // 获取课程列表
          this.course_list_url = this.$settings.host+"/course/list?";
          // 课程分类
          if(this.filter.cate!=0){
            this.course_list_url += `course_category=${this.filter.cate}&`;
          }

          // 默认排序
          if(this.filter.id){
            this.course_list_url+= `ordering=-id&`;
          }

          // 人气
          if(this.filter.hots){
            this.course_list_url+= `ordering=-students&`;
          }

          // 价格
          if(this.filter.price==1){
            this.course_list_url+= `ordering=price&`;
          }else if(this.filter.price==2){
            this.course_list_url+= `ordering=-price&`;
          }

          this.$axios.get(this.course_list_url).then(response=>{
            this.course_list = response.data;
          }).catch(error=>{
            console.log(error.response)
          });
      }
    },
    created(){
      // 获取课程分类
      this.$axios.get(this.$settings.host+"/course/cate").then(response=>{
        this.cate_list = response.data;
      }).catch(error=>{
        console.log(error.response)
      });

      // 获取课程
      this.get_course_list()

    },
    filters: {
        catcode: function(value) {
          if (value && value.length > 8) {          //字符最大长度
            value = value.substring(0, 8) + "...";  //超过省略
          }
          return value;
        },
      },
  }
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值