Python笔记_74_用户的注册认证_注册功能的实现_云通讯发送短信验证码

用户的注册认证

前端显示注册页面

调整首页头部和登陆页面的注册按钮的链接。

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

<template>
	<div class="box">
		<img src="/static/image/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">
          <input v-model="password" type="password" placeholder="输入密码" class="user">
					<input v-model="sms" type="text" placeholder="输入验证码" class="user">
          <div id="geetest"></div>
					<button class="register_btn" >注册</button>
					<p class="go_login" >已有账号 <router-link to="/user/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;
	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-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{
    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:[
    // 路由列表
	...
    {
      path: "/user/register",
      name:"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>

注册功能的实现

视图代码:

from rest_framework.generics import CreateAPIView
from .models import User
from .seriazliers import UserModelSerializer
class UserAPIView(CreateAPIView):
    queryset = User.objects.filter(is_active=True).all()
    serializer_class = UserModelSerializer

序列化器,users子应用下创建sreializers.py文件,代码:

from rest_framework import serializers
from .models import User
class UserModelSerializer(serializers.ModelSerializer):
    """用户注册的序列化器"""
    # 字段声明
    sms_code = serializers.CharField(write_only=True, max_length=6, help_text="短信验证码")
    token = serializers.CharField(max_length=1024, read_only=True, help_text="jwt的token字符串")

    # 模型信息
    class Meta:
        model = User
        fields = ["id", "mobile", "password", "sms_code", "token"]
        extra_kwargs = {
            "id":{
              "read_only":True,
            },
            "mobile":{
                "max_length": 15,
                "required": True
            },
            "password":{
                "write_only": True,
                "max_length": 128,
                "required": True
            }
        }

    # 验证数据


    # 保存信息
    def create(self, validated_data):
        """添加用户"""
        # 删除不存在于数据库的字段
        del validated_data["sms_code"]

        # 保存用户信息,设置一些字段的默认值
        validated_data["username"] = validated_data["mobile"]

        # 调用当前模型序列化器父类的create
        user = super().create(validated_data)

        # 生成jwt的token值,用于记录登录状态
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)

        # 最终token作为user模型的一个字段返回给客户端
        user.token = jwt_encode_handler(payload)

        return user

路由地址

from django.urls import path, re_path
from . import views
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
    path(r'authorizations/', obtain_jwt_token, name='authorizations'),
    path(r'captcha/', views.CaptchaAPIView.as_view()),
    path(r'', views.UserAPIView.as_view() ),
]

客户端提交注册信息

接下来,我们需要再注册页面中提供发送短信验证的功能,所以页面进行调整,代码:

<template>
	<div class="box">
		<img src="/static/image/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">
          <input v-model="password" type="password" placeholder="输入密码" class="user">
					<div class="sms_code">
            <input v-model="sms" type="text" maxlength="6" placeholder="输入验证码" class="user">
            <span class="code_text">点击发送短信</span>
          </div>
          <div id="geetest"></div>
					<button class="register_btn" @click="registerHander">注册</button>
					<p class="go_login" >已有账号 <router-link to="/user/login">直接登录</router-link></p>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
export default {
  name: 'Register',
  data(){
    return {
        sms:"",
        mobile:"",
        password:"",
        validateResult:false,
    }
  },
  created(){
  },
  methods:{
      registerHander(){
          // 用户注册
          // 1. 接受验证数据
          if( !/1[3-9]\d{9}/.test(this.mobile) ){
              this.$message("对不起,手机号有误!");
          }
          if( this.password.length < 6 || this.password.length > 16 ){
              this.$message("对不起,密码必须保持6-16位字符之间");
          }

          if( this.sms.length != 6 ){
              this.$message("对不起,短信验证码有误!");
          }

          // 2. 发送ajax
          this.$axios.post(`${this.$settings.Host}/user/`,{
              mobile:this.mobile,
              password:this.password,
              sms_code:this.sms
          }).then(response=>{
              // 保存登录状态
              sessionStorage.user_id = response.data.id;
              sessionStorage.user_name = response.data.mobile;
              sessionStorage.user_token = response.data.token;
              let self = this;
              this.$alert("欢迎注册路飞学城!","注册成功",{
                  callback(){
                      self.$router.push("/");
                  }
              })
          })
      }
  },

};
</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;
	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-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{
    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;
}
.sms_code{
    position: relative;
}
.code_text{
    position: absolute;
    right: 14px;
    top: 13px;
    border-left: 1px solid orange;
    padding-left: 14px;
    cursor: pointer;
    background-color: #fff;
}
</style>

接着,我们就把注册过程中redis数据库的相关配置完成。

如果需要再django中直接通过代码操作redis,需要安装django-redis

这个模块是基于pyredis来完成。pyredis就是在python中操作redis的最常用模块。

它会把redis的所有命令作为函数名提供给开发者使用,每一个命令函数的参数就是终端里面的命令参数。

pip install django-redis

settings/dev.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:xxx
AUTH TOKEN : xxx
AppID(默认):xxx
Rest URL(生产): app.cloopen.com:8883         [项目上线时使用真实短信发送服务器]
Rest URL(开发): sandboxapp.cloopen.com:8883  [项目开发时使用沙箱短信发送服务器]

找到sdkdemo进行下载

[外链图片转存失败(img-lCcVotqd-1565782353831)(assets/1553677987640.png)]

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

[外链图片转存失败(img-OwnJnfWc-1565782353833)(assets/1553678528811.png)]

后端生成短信验证码

settings/dev.py配置

# 短信验证码配置
SMS_ACCOUNTSID = "8aa*************************d228e"
SMS_ACCOUNTTOKEN = "62fc*************************03de"
SMS_APPID = "8aaf*************************f782295"
SMS_SERVERIP = "sandboxapp.cloopen.com"
SMS_EXPIRE_TIME = 300
SMS_INTERVAL_TIME = 60
SMS_TEMPLATE_ID = 1

users/views.py视图文件

from rest_framework.views import APIView
from luffyapi.libs.geetest import GeetestLib
from rest_framework.response import Response
from django.conf import settings

class CaptchaAPIView(APIView):
    """极验验证码"""
    def get(self,request):
        """生成验证码的流水号和状态"""
        gt = GeetestLib(settings.PC_GEETEST_ID, settings.PC_GEETEST_KEY)
        status = gt.pre_process(settings.PC_GEETEST_USER_ID)
        response_str = gt.get_response_str()
        return Response(response_str)

    def post(self,request):
        """二次验证"""
        gt = GeetestLib(settings.PC_GEETEST_ID, settings.PC_GEETEST_KEY)
        challenge = request.data.get(gt.FN_CHALLENGE, '')
        validate = request.data.get(gt.FN_VALIDATE, '')
        seccode = request.data.get(gt.FN_SECCODE, '')

        result = gt.success_validate(challenge, validate, seccode, settings.PC_GEETEST_USER_ID)
        if not result:
            result = gt.failback_validate(challenge, validate, seccode)

        return Response({"status": result})


from rest_framework.generics import CreateAPIView
from .models import User
from .seriazliers import UserModelSerializer
class UserAPIView(CreateAPIView):
    queryset = User.objects.filter(is_active=True).all()
    serializer_class = UserModelSerializer
   


"""
/users/sms/13112345678
"""
from rest_framework import status
import random
from django_redis import get_redis_connection
from luffyapi.libs.yuntongxun.sms import CCP
class SMSCodeAPIView(APIView):
    def get(self,request,mobile):
        """发送短信"""
        # 1. 验证手机号是否已经注册过
        try:
            User.objects.get(mobile=mobile)
            return Response({"message": "对不起,当前手机号已经被注册"}, status=status.HTTP_400_BAD_REQUEST)
        except User.DoesNotExist:
            # 如果手机号不存在于数据库,则表示没有注册,不进行任何处理
            pass

        # 2. 验证短信的发送间隔时间[60s]
        # 2.1 链接redis
        redis = get_redis_connection("sms_code")

        # 使用get获取指定键的值,如果获取不到,则返回None
        interval = redis.get("exp_%s" % mobile)
        if interval:
            return Response({"message": "对不起,短信发送间隔太短!"}, status=status.HTTP_403_FORBIDDEN)

        # 3.1 生成随机的短信验证码
        sms_code = "%06d" % random.randint(0,999999)

        # 3.2 保存发送的验证码到redis中[手机号码、短信验证码、短信发送间隔、短信有效期]
        """
        字符串
            setex sms_手机号 300 短信验证码
            setex exp_手机号 60  _
        """
        redis.setex("sms_%s" % mobile, settings.SMS_EXPIRE_TIME, sms_code)
        redis.setex("exp_%s" % mobile, settings.SMS_INTERVAL_TIME, "_")

        # 3.3 调用sdk发送短信
        ccp = CCP()
        result = ccp.send_template_sms(mobile, [sms_code, settings.SMS_EXPIRE_TIME//60 ], settings.SMS_TEIMPLATE_ID)

        # 4. 返回发送短信的结果
        if result == -1:
            return Response({"message":"短信发送失败!"},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            return Response({"message":"短信发送成功!"},status=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', 'password','password2')
        extra_kwargs={
            "password":{
                "write_only":True
            }
        }

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[345789]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')

        # 验证手机号是否已经被注册了
        # try:
        #     user = User.objects.get(mobile=value)
        # except:
        #     user = None
        #
        # if user:
        #     raise serializers.ValidationError('当前手机号已经被注册')

        # 上面验证手机号是否存在的代码[优化版]
        try:
            User.objects.get(mobile=value)
            # 如果有获取到用户信息,则下面的代码不会被执行,如果没有获取到用户信息,则表示手机号没有注册过,可以直接pass
            raise serializers.ValidationError('当前手机号已经被注册')
        except:
            pass

        return value

    def validate(self,data):
        # 验证密码
        password = data.get("password")
        password2 = data.get("password2")
        if len(password)<6:
            raise serializers.ValidationError('密码太短不安全~')

        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

# 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

# 子应用路由 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>


注意
发送验证码测试过程中如果出现HTTP 403错误,清除本地cookie再试。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值