登入註冊頁面
阿新 • • 發佈:2021-01-08
前提:基於element-ui環境
模態登入元件
|
|
模態註冊元件
|
|
導航條:結合實際情況完成樣式
|
|
登入業務分析
多方式登入
|
|
驗證碼登入
|
|
註冊業務分析
驗證碼註冊
|
|
彙總
|
|
# 昨日回顧 ```python 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 ```html <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 ```html <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 多方式登入介面 ```python 1 多方式登入介面 2 簡訊登入介面 3 簡訊註冊介面 4 驗證手機號是否存在介面 5 傳送簡訊驗證碼介面 ``` ### 3.1 路由層 ```python from rest_framework.routers import SimpleRouter router=SimpleRouter() router.register('',views.LoginView,basename='loginview') urlpatterns = [ ] urlpatterns+=router.urls ``` ### 3.2 檢視層 ```python 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 序列化類 ```python 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 手機號是否存在介面 ```python # 路由層 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 簡訊驗證碼介面 ```python 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) ```View Code