Luffy /4/ 多方式登入介面&登入註冊前端頁面

HammerZe發表於2022-04-24

Luffy /4/ 多方式登入介面&登入註冊前端頁面

現在比較常見的登入方式:手機號+驗證碼,郵箱+密碼,使用者名稱+密碼,下面實現一下多方式登入介面

需求介面

# 登陸和註冊功能--->5個介面
-多方式登陸介面(手機號,郵箱,使用者名稱 +密碼)
-驗證手機號是否存在介面
  
-傳送簡訊驗證碼介面 # 藉助於第三方傳送簡訊:阿里,騰訊,容聯雲通訊,剛註冊會送100條簡訊
-手機號+驗證碼登陸介面
-手機號+驗證碼+密碼註冊介面

騰訊雲簡訊

這裡的簡訊功能使用的是第三方騰訊雲,註冊公眾號申請騰訊雲簡訊功能,會送100條簡訊供你玩;

申請好公眾號,通過該地址https://console.cloud.tencent.com/smsv2/guide,設定

"""
建立簡訊簽名
	-簽名管理---》建立簽名--》使用公眾號提交申請---》稽核
建立簡訊正文模板
	-正文模板管理---》建立正文模板--》等稽核
傳送簡訊
	-API,SDK
"""

?官網文件

API和SDK區別

-API介面,通過HTTP呼叫騰訊雲傳送簡訊介面,騰訊負責把簡訊傳送到手機上,HTTP介面基於它來寫,比較麻煩,需要我們處理請求引數,或者攜帶很多引數···

-SDK:第三方使用不同語言封裝好了,只需下載匯入,呼叫函式處理即可

使用SDK

# 發簡訊sdk的使用
# 3.x的傳送簡訊sdk,tencentcloud 包含的功能更多
pip install tencentcloud-sdk-python
# 2.x傳送簡訊sdk:https://cloud.tencent.com/document/product/382/11672
# 只是發簡訊的sdk,功能少,py3.8以後不支援
pip install qcloudsms_py

登入註冊前端頁面

在實現頁面前我們思考如下問題:

如何實現點選登入或圖片進行跳轉

# 思路:使用vue-router實現頁面跳轉,跳轉就涉及到路由,我們可以先把路由配置好

1.router/index.js中配置要跳轉的路由,這裡登入舉例,寫一個Login元件(登入頁面),然後在index.js匯入使用:import Login from "@/views/Login";
"""
{
        path: '/login',
        name: 'login',
        component: Login
    }
"""
2. 訪問/login路徑就能夠跳轉到登入頁面元件
    
    
# 實現點選跳轉的兩種常用方法
## 方法一:繫結點選事件,實現點選跳轉
   this.$router.push('/login')
## 方法二:使用 <router-link to=""></router-link>標籤實現跳轉
  註冊:<router-link to="/login"><span>註冊</span></router-link>
  圖片:<router-link to="/">
         <img src="../assets/img/head-logo.svg" alt="">
        </router-link>  

<router-link to=""></router-link>標籤實現跳轉第三方

資料庫新增第三方link

image-20220424202619568

demo

<!--  跳第三方  -->
<!--如果圖片的跳轉路徑不包含http,那麼就跳轉本地 -->
<div v-if="!(item.link.indexOf('http')>-1)">
	<router-link :to="item.link">
        <img :src="item.image" alt="課程圖">
     </router-link>
</div>
<!-- 如果圖片包含了http那麼就跳轉第三方 -->
<div v-else>
	<a :href="item.link"> 
    <img :src="item.image" alt="課程圖">
    </a>
</div>

如果不進行處理,router-link標籤只能跳轉本地,如果想要跳轉第三方(百度,部落格···)需要進一步處理!


登入註冊前端頁面實現

實現的樣式是基於彈出框實現,彈出的是模態框

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>

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>

Header.vue

<template>
    <div class="header">
        <div class="slogan">
            <p>路飛學城 | 幫助有志向的年輕人通過努力學習獲得體面的工作和生活</p>
        </div>
        <div class="nav">
            <ul class="left-part">
                <li class="logo">
                    <router-link to="/">
                        <img src="../assets/img/head-logo.svg" alt="">
                    </router-link>
                </li>
                <li class="ele">
                    <span @click="goPage('/free-course')" :class="{active: url_path === '/free-course'}">免費課</span>
                </li>
                <li class="ele">
                    <span @click="goPage('/actual-course')" :class="{active: url_path === '/actual-course'}">實戰課</span>
                </li>
                <li class="ele">
                    <span @click="goPage('/light-course')" :class="{active: url_path === '/light-course'}">輕課</span>
                </li>
            </ul>

            <div class="right-part">
                <div>
                    <span @click="put_login">登入</span>
                    <span class="line">|</span>
                    <span @click="put_register">註冊</span>
                </div>
            </div>
            <Login v-if="is_login" @close="close_login" @go="put_register"/>
            <Register v-if="is_register" @close="close_register" @go="put_login"/>


        </div>
    </div>

</template>

<script>
    import Login from "@/components/Login";
    import Register from "@/components/Register";

    export default {
        name: "Header",
        data() {
            return {
                url_path: sessionStorage.url_path || '/',
                is_login: false,
                is_register: false
            }
        },
        methods: {
            goPage(url_path) {
                // 已經是當前路由就沒有必要重新跳轉
                if (this.url_path !== url_path) {
                    this.$router.push(url_path);
                }
                sessionStorage.url_path = url_path;
            },
            close_login() {
                this.is_login = false
            },
            close_register() {
                this.is_register = false
            },
            put_register() {
                this.is_register = true
                this.is_login = false
            },
            put_login() {
                this.is_register = false
                this.is_login = true
            }

        },
        created() {
            sessionStorage.url_path = this.$route.path;
            this.url_path = this.$route.path;
        },
        components: {
            Login, Register
        }
    }
</script>

<style scoped>
    .header {
        background-color: white;
        box-shadow: 0 0 5px 0 #aaa;
    }

    .header:after {
        content: "";
        display: block;
        clear: both;
    }

    .slogan {
        background-color: #eee;
        height: 40px;
    }

    .slogan p {
        width: 1200px;
        margin: 0 auto;
        color: #aaa;
        font-size: 13px;
        line-height: 40px;
    }

    .nav {
        background-color: white;
        user-select: none;
        width: 1200px;
        margin: 0 auto;

    }

    .nav ul {
        padding: 15px 0;
        float: left;
    }

    .nav ul:after {
        clear: both;
        content: '';
        display: block;
    }

    .nav ul li {
        float: left;
    }

    .logo {
        margin-right: 20px;
    }

    .ele {
        margin: 0 20px;
    }

    .ele span {
        display: block;
        font: 15px/36px '微軟雅黑';
        border-bottom: 2px solid transparent;
        cursor: pointer;
    }

    .ele span:hover {
        border-bottom-color: orange;
    }

    .ele span.active {
        color: orange;
        border-bottom-color: orange;
    }

    .right-part {
        float: right;
    }

    .right-part .line {
        margin: 0 10px;
    }

    .right-part span {
        line-height: 68px;
        cursor: pointer;
    }
</style>

image-20220424225146317

image-20220424225202423

介面實現1

驗證手機號是否存在介面

思路:資料庫查詢,存在返回{“code”:“100”,“msg”:“成功”}

users/views.py

from .models import User
from utils.reponse import APIResponse
from rest_framework.exceptions import APIException
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action

class MobilePhone(ViewSet):
    @action(methods=['GET'],detail=False)
    def check_mobile(self,request):
        try:
            # 從請求引數獲取手機號
            mobile = request.query_params.get('mobile')
            User.objects.get(mobile=mobile)
            # 存在返回`{“code”:“100”,“msg”:“成功”}`
            return APIResponse()
        except Exception as e:
            raise APIException(str(e))

users/urls.py


from django.urls import path, include
from rest_framework.routers import SimpleRouter
from .views import UserView

router = SimpleRouter()
# 127.0.0.1:8000/api/v1/user/mobile/check_mobile
router.register('mobile',UserView , 'mobile')
urlpatterns = [
    path('', include(router.urls)),
]

image-20220424193157883


多方式登入介面

檢視

from .models import User
from utils.reponse import APIResponse
from rest_framework.exceptions import APIException
from rest_framework.viewsets import ViewSet,GenericViewSet
from rest_framework.decorators import action


# 驗證手機號是否存在
class MobileView(ViewSet):
    @action(methods=['GET'],detail=False)
    def check_mobile(self,request):
        try:
            # 從請求引數獲取手機號
            mobile = request.query_params.get('mobile')
            User.objects.get(mobile=mobile)
            # 存在返回`{“code”:“100”,“msg”:“成功”}`
            return APIResponse()
        except Exception as e:
            raise APIException(str(e))


# 多方式登入
from .serializer import MulLoginSerializer


class LoginView(GenericViewSet):
    serializer_class = MulLoginSerializer
    queryset = User

    # 兩個登陸方式都寫在這裡面(多方式,一個是驗證碼登陸)
    # login不是儲存,但是用post,我們們的想法是把驗證邏輯寫到序列化類中
    @action(methods=["post"], detail=False)
    def mul_login(self, request):
        try:
            ser = MulLoginSerializer(data=request.data, context={'request': request})
            ser.is_valid(raise_exception=True)  # 如果校驗失敗,直接拋異常,不需要加if判斷了
            token = ser.context.get('token')
            username = ser.context.get('username')
            icon = ser.context.get('icon')
            return APIResponse(token=token, username=username, icon=icon)  # {code:100,msg:成功,token:dsadsf,username:Hammer}
        except Exception as e:
            raise APIException(str(e))

序列化類

from .models import User
from rest_framework import serializers
from rest_framework.exceptions import ValidationError


# 這個序列化類,只用來做反序列化,資料校驗,最後不儲存,不用來做序列化
class MulLoginSerializer(serializers.ModelSerializer):
    # 一定要重寫username這個欄位,因為username這個欄位校驗規則是從User表對映過來的,
    # username是唯一,假設資料庫中存在HammerZe使用者,傳入HammerZe使用者,欄位自己的校驗規則就會校驗失敗,失敗原因是資料庫存在一個HammerZe使用者了
    # 所以需要重寫這個欄位,取消 掉它的unique
    username = serializers.CharField(max_length=18, min_length=3)  # 一定要重寫,不重寫,欄位自己的校驗過不去,就到不了全域性鉤子

    class Meta:
        model = User
        fields = ['username', 'password']

    def validate(self, attrs):
        # 在這裡面完成校驗,如果校驗失敗,直接拋異常
        # 1 多方式得到user
        user = self._get_user(attrs)
        # 2  user簽發token
        token = self._get_token(user)
        # 3  把token,username,icon放到context中
        self.context['token'] = token
        self.context['username'] = user.username
        # 寫死的路徑
        # self.context['icon'] = 'http://127.0.0.1:8000/media/'+str(user.icon)  # 物件ImageField的物件
        request = self.context['request']
        # request.META['HTTP_HOST']取出服務端的ip地址
        icon = 'http://%s/media/%s' % (request.META['HTTP_HOST'], str(user.icon))
        self.context['icon'] =icon
        return attrs

    # 正則校驗登入方式
    # 意思是該方法只在類內部用,但是外部也可以用,如果寫成__就只能再內部用了
    def _get_user(self, attrs):
        import re
        username = attrs.get('username')
        if re.match(r'^1[3-9][0-9]{9}$', username):
            user = User.objects.filter(mobile=username).first()
        elif re.match(r'^.+@.+$', username):
            user = User.objects.filter(email=username).first()
        else:
            user = User.objects.filter(username=username).first()

        if not user:
            # raise ValidationError('使用者不存在')
            raise ValidationError('使用者名稱或密碼錯誤')

        # 取出前端傳入的密碼
        password = attrs.get('password')
        if not user.check_password(password):  # 學auth時講的,通過明文校驗密碼
            raise ValidationError("使用者名稱或密碼錯誤")

        return user

    def _get_token(self, user):
        # jwt模組中提供的
        from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return token

路由

from django.urls import path,include
from user import views
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('mobile',views.MobileView,'mobile')  #  127.0.0.1:8000/api/v1/user/mobile/check_mobile
router.register('login',views.LoginView , 'login')  #  127.0.0.1:8000/api/v1/user/login/mul_login
urlpatterns = [
    path('',include(router.urls)),
]

測試

image-20220424224350744

image-20220424224611093

image-20220424224629432


介面實現2

實現傳送簡訊介面配置和驗證

配置傳送簡訊

\libs\tencent_sms_v3_init_.py

from .sms import get_code, send_sms

\libs\tencent_sms_v3\sms.py

import random
from . import settings
from utils.log import logger
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 匯入對應產品模組的client models。
from tencentcloud.sms.v20210111 import sms_client, models

# 匯入可選配置類
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile


# 寫兩個函式,
# 獲取驗證碼的函式
def get_code(count=4):
    code_str = ''
    for i in range(count):
        num = random.randint(0, 9)
        code_str += str(num)
    return code_str


# 傳送簡訊的函式

def send_sms(phone, code):
    try:
        cred = credential.Credential(settings.SECRETID, settings.SECRETKEY)
        # 例項化一個http選項,可選的,沒有特殊需求可以跳過。
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post請求(預設為post請求)
        httpProfile.reqTimeout = 30  # 請求超時時間,單位為秒(預設60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(預設就近接入)
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定簽名演算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
        req = models.SendSmsRequest()
        req.SmsSdkAppId = settings.APPID
        req.SignName = settings.SIGNAME
        req.TemplateId = settings.TemplateId
        req.TemplateParamSet = [code,]
        req.PhoneNumberSet = ["+86%s"%phone,]
        req.SessionContext = ""
        req.ExtendCode = ""
        req.SenderId = ""
        client.SendSms(req)
        # print(resp.to_json_string(indent=2))
        return True
    except TencentCloudSDKException as err:
        # 如果簡訊傳送失敗,記錄一下日誌--》一旦使用了記錄日誌,使用的是django 的日誌,以後這個包,給別的框架用,要改日誌
        logger.error('手機號為:%s傳送簡訊失敗,失敗原因:%s'%phone,str(err))

tencent_sms_v3\settings.py

# 都配置成自己的就行了,參考官網文件https://console.cloud.tencent.com/cam/capi
# https://cloud.tencent.com/document/product/382/43196
SECRETID=''
SECRETKEY=''
APPID = ""
SIGNAME=''
TemplateId = ""

傳送簡訊介面

檢視

from libs import tencent_sms_v3

class SendSmsView(ViewSet):
    @action(methods=['GET'],detail=False)
    def send_message(self, request):
        try:
            phone = request.query_params.get('phone')
            # 生成驗證碼
            code = tencent_sms_v3.get_code()
            # code要儲存,否則後面沒法驗證
            res = tencent_sms_v3.send_sms(phone, code)
            if res:
                return APIResponse(msg='簡訊傳送成功')
            else:
                raise APIException("簡訊傳送失敗")
        except Exception as e:
            raise APIException(str(e))

路由

router.register('send',views.SendSmsView , 'send')  #  127.0.0.1:8000/api/v1/user/send/send_message/--->get請求

測試

image-20220424233417661

相關文章