166-路飞07-登录注册前端&多方式登录接口&短信验证码

昨日回顾

https://gitee.com/liuqingzheng/luffycity.git
https://gitee.com/liuqingzheng/luffyapi.git
    
1 git操作 (其中架构,两个合作,gitee)
2 git add .
3 git commit -m '注释'
4 fetch和pull 
	-git fetch 相当于是从远程获取最新到本地,不会自动merge
    -git pull 相当于从远程获取最新版本并merge到本地
	-在实际使用中,git fetch更安全一些
5 变基:优化分支日志
6 ssh和https连接方式:公司常用(gitlab),领导会问你要一个公钥,给你一个地址
7 连接远程分支
	git add .
    git commit -m ‘详细写’
    git pull origin dev/master
    有冲突解决冲突,没有冲突直接提交
    git push origin dev  (确认好自己在哪个分支上)
8 冲突出现原因(勤拉,比你同事早提交)
	-多个人开发同一分支
    -不同分支合并

今日内容

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 发送短信验证码接口

3.1 路由层

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

3.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='用户名或密码错误')

3.2 序列化类

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)

你可能感兴趣的:(Django,git,Vue)