码迷,mamicode.com
首页 > 移动开发 > 详细

vue框架前后端分离项目之登录注册页面及多方式登录、手机号验证码接口等相关内容-121

时间:2021-01-02 11:31:20      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:try   sms   hover   data   black   验证码   软件开发工具   note   none   

1 登录注册前端页面

1.1 Login.vue

<template>
<div class="login">
       <div class="box">
           <i class="el-icon-close" @click="close_login"></i>
           <div class="content">
               <div class="nav">
                   <span :class="{active: login_method === ‘is_pwd‘}"
                         @click="change_login_method(‘is_pwd‘)">密码登录</span>
                   <span :class="{active: login_method === ‘is_sms‘}"
                         @click="change_login_method(‘is_sms‘)">短信登录</span>
               </div>
               <el-form v-if="login_method === ‘is_pwd‘">
                   <el-input
                           placeholder="用户名/手机号/邮箱"
                           prefix-icon="el-icon-user"
                           v-model="username"
                           clearable>
                   </el-input>
                   <el-input
                           placeholder="密码"
                           prefix-icon="el-icon-key"
                           v-model="password"
                           clearable
                           show-password>
                   </el-input>
                   <el-button type="primary">登录</el-button>
               </el-form>
               <el-form v-if="login_method === ‘is_sms‘">
                   <el-input
                           placeholder="手机号"
                           prefix-icon="el-icon-phone-outline"
                           v-model="mobile"
                           clearable
                           @blur="check_mobile">
                   </el-input>
                   <el-input
                           placeholder="验证码"
                           prefix-icon="el-icon-chat-line-round"
                           v-model="sms"
                           clearable>
                       <template slot="append">
                           <span class="sms" @click="send_sms">{{ sms_interval }}</span>
                       </template>
                   </el-input>
                   <el-button type="primary">登录</el-button>
               </el-form>
               <div class="foot">
                   <span @click="go_register">立即注册</span>
               </div>
           </div>
       </div>
   </div>
</template>
?
<script>
 export default {
       name: "Login",
       data() {
           return {
               username: ‘‘,
               password: ‘‘,
               mobile: ‘‘,
               sms: ‘‘,
               login_method: ‘is_pwd‘,
               sms_interval: ‘获取验证码‘,
               is_send: false,
          }
      },
       methods: {
           close_login() {
               this.$emit(‘close‘)
          },
           go_register() {
               this.$emit(‘go‘)
          },
           change_login_method(method) {
               this.login_method = method;
          },
           check_mobile() {
               if (!this.mobile) return;
               if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
                   this.$message({
                       message: ‘手机号有误‘,
                       type: ‘warning‘,
                       duration: 1000,
                       onClose: () => {
                           this.mobile = ‘‘;
                      }
                  });
                   return false;
              }
               this.is_send = true;
          },
           send_sms() {
?
               if (!this.is_send) return;
               this.is_send = false;
               let sms_interval_time = 60;
               this.sms_interval = "发送中...";
               let timer = setInterval(() => {
                   if (sms_interval_time <= 1) {
                       clearInterval(timer);
                       this.sms_interval = "获取验证码";
                       this.is_send = true; // 重新回复点击发送功能的条件
                  } else {
                       sms_interval_time -= 1;
                       this.sms_interval = `${sms_interval_time}秒后再发`;
                  }
              }, 1000);
          }
      }
  }
</script>
?
<style scoped>
.login {
       width: 100vw;
       height: 100vh;
       position: fixed;
       top: 0;
       left: 0;
       z-index: 10;
       background-color: rgba(0, 0, 0, 0.3);
  }
?
   .box {
       width: 400px;
       height: 420px;
       background-color: white;
       border-radius: 10px;
       position: relative;
       top: calc(50vh - 210px);
       left: calc(50vw - 200px);
  }
?
   .el-icon-close {
       position: absolute;
       font-weight: bold;
       font-size: 20px;
       top: 10px;
       right: 10px;
       cursor: pointer;
  }
?
   .el-icon-close:hover {
       color: darkred;
  }
?
   .content {
       position: absolute;
       top: 40px;
       width: 280px;
       left: 60px;
  }
?
   .nav {
       font-size: 20px;
       height: 38px;
       border-bottom: 2px solid darkgrey;
  }
?
   .nav > span {
       margin: 0 20px 0 35px;
       color: darkgrey;
       user-select: none;
       cursor: pointer;
       padding-bottom: 10px;
       border-bottom: 2px solid darkgrey;
  }
?
   .nav > span.active {
       color: black;
       border-bottom: 3px solid black;
       padding-bottom: 9px;
  }
?
   .el-input, .el-button {
       margin-top: 40px;
  }
?
   .el-button {
       width: 100%;
       font-size: 18px;
  }
?
   .foot > span {
       float: right;
       margin-top: 20px;
       color: orange;
       cursor: pointer;
  }
?
   .sms {
       color: orange;
       cursor: pointer;
       display: inline-block;
       width: 70px;
       text-align: center;
       user-select: none;
  }
</style>

 

1.2 Register.vue

<template>
   <div class="register">
       <div class="box">
           <i class="el-icon-close" @click="close_register"></i>
           <div class="content">
               <div class="nav">
                   <span class="active">新用户注册</span>
               </div>
               <el-form>
                   <el-input
                           placeholder="手机号"
                           prefix-icon="el-icon-phone-outline"
                           v-model="mobile"
                           clearable
                           @blur="check_mobile">
                   </el-input>
                   <el-input
                           placeholder="密码"
                           prefix-icon="el-icon-key"
                           v-model="password"
                           clearable
                           show-password>
                   </el-input>
                   <el-input
                           placeholder="验证码"
                           prefix-icon="el-icon-chat-line-round"
                           v-model="sms"
                           clearable>
                       <template slot="append">
                           <span class="sms" @click="send_sms">{{ sms_interval }}</span>
                       </template>
                   </el-input>
                   <el-button type="primary">注册</el-button>
               </el-form>
               <div class="foot">
                   <span @click="go_login">立即登录</span>
               </div>
           </div>
       </div>
   </div>
</template>
?
<script>
   export default {
       name: "Register",
       data() {
           return {
               mobile: ‘‘,
               password: ‘‘,
               sms: ‘‘,
               sms_interval: ‘获取验证码‘,
               is_send: false,
          }
      },
       methods: {
           close_register() {
               this.$emit(‘close‘, false)
          },
           go_login() {
               this.$emit(‘go‘)
          },
           check_mobile() {
               if (!this.mobile) return;
               if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
                   this.$message({
                       message: ‘手机号有误‘,
                       type: ‘warning‘,
                       duration: 1000,
                       onClose: () => {
                           this.mobile = ‘‘;
                      }
                  });
                   return false;
              }
               this.is_send = true;
          },
           send_sms() {
               if (!this.is_send) return;
               this.is_send = false;
               let sms_interval_time = 60;
               this.sms_interval = "发送中...";
               let timer = setInterval(() => {
                   if (sms_interval_time <= 1) {
                       clearInterval(timer);
                       this.sms_interval = "获取验证码";
                       this.is_send = true; // 重新回复点击发送功能的条件
                  } else {
                       sms_interval_time -= 1;
                       this.sms_interval = `${sms_interval_time}秒后再发`;
                  }
              }, 1000);
          }
      }
  }
</script>
?
<style scoped>
   .register {
       width: 100vw;
       height: 100vh;
       position: fixed;
       top: 0;
       left: 0;
       z-index: 10;
       background-color: rgba(0, 0, 0, 0.3);
  }
?
   .box {
       width: 400px;
       height: 480px;
       background-color: white;
       border-radius: 10px;
       position: relative;
       top: calc(50vh - 240px);
       left: calc(50vw - 200px);
  }
?
   .el-icon-close {
       position: absolute;
       font-weight: bold;
       font-size: 20px;
       top: 10px;
       right: 10px;
       cursor: pointer;
  }
?
   .el-icon-close:hover {
       color: darkred;
  }
?
   .content {
       position: absolute;
       top: 40px;
       width: 280px;
       left: 60px;
  }
?
   .nav {
       font-size: 20px;
       height: 38px;
       border-bottom: 2px solid darkgrey;
  }
?
   .nav > span {
       margin-left: 90px;
       color: darkgrey;
       user-select: none;
       cursor: pointer;
       padding-bottom: 10px;
       border-bottom: 2px solid darkgrey;
  }
?
   .nav > span.active {
       color: black;
       border-bottom: 3px solid black;
       padding-bottom: 9px;
  }
?
   .el-input, .el-button {
       margin-top: 40px;
  }
?
   .el-button {
       width: 100%;
       font-size: 18px;
  }
?
   .foot > span {
       float: right;
       margin-top: 20px;
       color: orange;
       cursor: pointer;
  }
?
   .sms {
       color: orange;
       cursor: pointer;
       display: inline-block;
       width: 70px;
       text-align: center;
       user-select: none;
  }
</style>

2 多方式登录接口

1 多方式登录接口
2 短信登录接口
3 短信注册接口
4 验证手机号是否存在接口
5 发送短信验证码接口
?

2.1 路由层

from rest_framework.routers import SimpleRouter
router=SimpleRouter()
router.register(‘‘,views.LoginView,basename=‘loginview‘)
urlpatterns = [
]
urlpatterns+=router.urls

2.2 视图层

class LoginView(ViewSet):
   @action(methods=[‘post‘,],detail=False)
   def login(self, request, *args, **kwargs):
       ser = serializer.LoginSerialzer(data=request.data,context={‘request‘:request})
       if ser.is_valid():
           token = ser.context[‘token‘]
           user = ser.context[‘user‘]
           icon = ser.context[‘icon‘]
           return APIResponse(token=token, username=user.username, icon=icon,id=user.id)
       else:
           return APIResponse(status=1, msg=‘用户名或密码错误‘)

2.3 序列化类

from rest_framework import serializers
from . import models
from rest_framework.exceptions import ValidationError
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler
from django.conf import settings
?
class LoginSerialzer(serializers.ModelSerializer):
   username = serializers.CharField()  # 数据库中唯一字段
?
   class Meta:
       model = models.User
       fields = [‘id‘, ‘username‘, ‘icon‘, ‘password‘]
       extra_kwargs = {
           ‘password‘: {‘write_only‘: True},
           ‘username‘: {‘write_only‘: True},
      }
?
   def _get_user(self, attrs):
       username = attrs.get(‘username‘)
       password = attrs.get(‘password‘)
       # 判断username是手机,邮箱,用户名
       import re
       if re.match(r‘^1[3-9][0-9]{9}$‘, username):
           # 手机登录
           user = models.User.objects.filter(mobile=username, is_active=True).first()
       elif re.match(r‘^.+@.+$‘, username):
           # 邮箱登录
           user = models.User.objects.filter(email=username, is_active=True).first()
       else:
           # 账号登录
           user = models.User.objects.filter(username=username, is_active=True).first()
       if user and user.check_password(password):  # 校验密码
           return user
       raise ValidationError(‘用户名或密码错误‘)
?
   def _get_token(self, user):
       payload = jwt_payload_handler(user)
       token = jwt_encode_handler(payload)
       return token
?
   def validate(self, attrs):
       # 校验逻辑写在这里面
       user = self._get_user(attrs)
       # 通过请求头格式化icon
       request = self.context[‘request‘]
       # request.META[‘HTTP_HOST‘]:服务器地址
       icon = ‘http://%s%s%s‘ % (request.META[‘HTTP_HOST‘], settings.MEDIA_URL, user.icon)
       # icon:http://127.0.0.1:8000/media/icon/default.png
?
       token = self._get_token(user)
       self.context[‘token‘] = token
       self.context[‘user‘] = user
       self.context[‘icon‘] = icon
       return attrs

 

3 手机号是否存在接口

# 路由层
from rest_framework.routers import SimpleRouter
router=SimpleRouter()
router.register(‘‘,views.LoginView,basename=‘loginview‘)
urlpatterns = [
]
?
urlpatterns+=router.urls
# 视图层
class LoginView(ViewSet):
   @action(methods=[‘get‘,],detail=False)
   def check_mobile(self,request, *args, **kwargs):
       mobile=request.GET.get(‘mobile‘)
       # 手机号是否合法(是不是一个手机号)
       import re
       if re.match(r‘^1[3-9][0-9]{9}$‘, mobile):
           # 查询手机号是否存在
           user=models.User.objects.filter(mobile=mobile).first()
           if user:
               return APIResponse(msg=‘手机号存在‘)
           else:
               return APIResponse(status=1,msg=‘手机号未注册‘)
       else:
           return APIResponse(status=1,msg=‘手机号不合法‘)

 

4 短信验证码接口

1 阿里大于短信,腾讯的短信平台
2 充钱买短信,腾讯给你提供接口,向他们接口发请求,腾讯给你手机发短信
?
3 使用腾讯短信平台步骤
   创建短信签名:申请一个公众号,把公众号的截图,上传,申请后台审核
   创建短信正文模板:填写模板,通过审核
   等待审核  :通过以后
   发送短信:https://cloud.tencent.com/document/product/382/11672
       
4 api和sdk的区别
-api是一堆http的接口,有了接口就可以调用接口发短信,跟语言无关
   -sdk:软件开发工具包,分语言,这个公司,帮你使用python封装好了,只需要调用它的固定的方法,就能完 成发短信
       
5 使用腾讯短信提供的sdk
pip install qcloudsms_py
   # 短信应用 SDK AppID
   appid = 1400009099  # SDK AppID 以1400开头
   # 短信应用 SDK AppKey
   appkey = "9ff91d87c2cd7cd0ea762f141975d1df37481d48700d70ac37470aefc60f9bad"
   # 需要发送短信的手机号码
   phone_numbers = ["21212313123", "12345678902", "12345678903"]
   # 短信模板ID,需要在短信控制台中申请
   template_id = 7839  # NOTE: 这里的模板 ID`7839` 只是示例,真实的模板 ID 需要在短信控制台中申请
   # 签名
   sms_sign = "腾讯云"  # NOTE: 签名参数使用的是`签名内容`,而不是`签名ID`。这里的签名"腾讯云"只是示例,真实的签名需要在短信控制台中申请
   from qcloudsms_py import SmsSingleSender
   from qcloudsms_py.httpclient import HTTPError
   ssender = SmsSingleSender(appid, appkey)
   params = ["5678"]  # 当模板没有参数时,`params = []`
   try:
     result = ssender.send_with_param(86, phone_numbers[0],
         template_id, params, sign=sms_sign, extend="", ext="")
   except HTTPError as e:
     print(e)
   except Exception as e:
     print(e)
   print(result)

 

 

vue框架前后端分离项目之登录注册页面及多方式登录、手机号验证码接口等相关内容-121

标签:try   sms   hover   data   black   验证码   软件开发工具   note   none   

原文地址:https://www.cnblogs.com/usherwang/p/14208576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!