Python 郵箱登錄驗證碼功能實現(xiàn)代碼
郵箱登錄:前端校驗與后端Redis緩存策略 ??
在構(gòu)建Web平臺時,郵箱登錄功能是用戶認證的重要環(huán)節(jié)。本文將介紹一種結(jié)合前端校驗和后端Redis緩存的郵箱登錄實現(xiàn)邏輯,旨在提高安全性和效率。
前言 ??
隨著互聯(lián)網(wǎng)服務(wù)的多樣化,用戶登錄方式也在不斷演進。郵箱登錄因其便捷性和普及性,成為了許多Web平臺的首選認證方式。本文將探討在實現(xiàn)郵箱登錄過程中,如何通過前端校驗和后端Redis緩存策略,提高登錄流程的安全性和效率。
前端郵箱輸入 ???
注:代碼不是完整代碼 因為涉及到其他模塊的引用 這里只是提供一個實現(xiàn)思路 具體代碼要根據(jù)項目去更改
<template> <el-form size="large" class="login-content-form" :model="state.ruleForm"> <el-form-item class="login-animation1" prop="email" :rules="[ { required: true, message: '請輸入郵箱地址', trigger: 'blur' }, { type: 'email', message: '請輸入正確的郵箱地址', trigger: ['blur', 'change'] } ]" > <el-input text placeholder="請輸入郵箱" v-model="state.ruleForm.email" clearable autocomplete="off"> <template #prefix> <i class="iconfont icon-dianhua el-input__icon"></i> </template> </el-input> </el-form-item> <el-form-item class="login-animation2"> <el-col :span="15"> <el-input text maxlength="4" placeholder="請輸入驗證碼" v-model="state.ruleForm.code" @keyup.enter="onSignIn" clearable autocomplete="off"> <template #prefix> <el-icon class="el-input__icon"> <ele-Position/> </el-icon> </template> </el-input> </el-col> <el-col :span="1"></el-col> <el-col :span="8"> <el-button v-waves class="login-content-code" @click="get_email_code" :disabled="isCountDownDisabled">{{ countDownText }}</el-button> </el-col> </el-form-item> <el-form-item class="login-animation3"> <el-button type="" class="login-content-submit" round v-waves style="background-color: #1e1e1e; color: #fff" @click="onSignIn" :loading="state.loading.signIn"> <span style="font-size: 1.2rem; font-weight: bolder">登 錄</span> </el-button> </el-form-item> </el-form> </template> <script setup name="loginEmail"> // 定義變量內(nèi)容 const storesThemeConfig = useThemeConfig(); const {themeConfig} = storeToRefs(storesThemeConfig); const route = useRoute(); const router = useRouter(); const state = reactive({ email_code: '', ruleForm: { email: '', code: '', }, loading: { signIn: false, }, }); // 時間獲取 const currentTime = computed(() => { return formatAxis(new Date()); }); // TODO: 驗證碼應(yīng)該設(shè)置過期 // 獲取郵箱驗證碼 const get_email_code = async () => { if (state.ruleForm.email.toLowerCase() === '') { ElMessage.error('請重新輸入郵箱'); return } // 觸發(fā)按鈕倒計時 countDownFunction(120); useUserApi().getCode({email: state.ruleForm.email}) .then(async res => { state.email_code = res.data; }) .catch((e) => { console.log('錯誤信息: ', e) }) }; const onSignIn = async () => { state.loading.signIn = true; console.log(state.ruleForm.code) console.log(state.email_code) if (state.ruleForm.code !== state.email_code) { ElMessage.error('驗證碼錯誤,請重新輸入'); state.ruleForm.code = ''; // 清空輸入框 state.loading.signIn = false; return } useUserApi().signIn({email: state.ruleForm.email}) .then(async res => { // 存儲token Session.set('token', res.data.token); // 存儲用戶信息 await useUserInfo().setUserInfos(); // 后端獲取菜單數(shù)據(jù) await initBackEndControlRoutes(); // 前端獲取菜單數(shù)據(jù) // await initFrontEndControlRoutes(); signInSuccess(false); }) .catch((e) => { console.log('錯誤信息: ', e) state.loading.signIn = false; }) }; // 登錄成功后的跳轉(zhuǎn) const signInSuccess = (isNoPower) => { if (isNoPower) { ElMessage.warning('抱歉,您沒有登錄權(quán)限'); Session.clear(); } else { // 初始化登錄成功時間問候語 let currentTimeInfo = currentTime.value; // 登錄成功,跳到轉(zhuǎn)首頁 // 如果是復(fù)制粘貼的路徑,非首頁/登錄頁,那么登錄成功后重定向到對應(yīng)的路徑中 if (route.query?.redirect) { router.push({ path: route.query?.redirect, query: Object.keys(route.query?.params).length > 0 ? JSON.parse(route.query?.params) : '', }); } else { router.push('/home'); } // 登錄成功提示 const signInText = '歡迎回來!'; ElMessage.success(`${currentTimeInfo},${signInText}`); // 添加 loading,防止第一次進入界面時出現(xiàn)短暫空白 NextLoading.start(); } state.loading.signIn = false; }; </script>
后端郵箱驗證碼發(fā)送 ??
生成驗證碼:在用戶請求發(fā)送驗證碼時,后端生成一個隨機的驗證碼。
def get_str_code(length=4): # 生成一個隨機的UUID random_uuid = uuid.uuid4() # 將UUID轉(zhuǎn)換為32位的十六進制字符串 code = random_uuid.hex # 截取指定長度的字符串 return code[:length]
發(fā)送驗證碼:通過郵件服務(wù)將驗證碼發(fā)送到用戶郵箱。
def send_email(config): send_to = config['send_to'] content = config['content'] subject = config['subject'] send_by = config['send_by'] mail_host = config['mail_host'] port = config['port'] mail_pass = config['mail_pass'] # 構(gòu)建郵件內(nèi)容 message = MIMEText(content, 'plain', 'utf-8') message['From'] = send_by # 發(fā)件人 message['To'] = send_to # 收件人 message['Subject'] = subject # 郵件主題 try: smtpObj = smtplib.SMTP_SSL(mail_host, port) # 啟用SSL發(fā)信, 端口一般是465 smtpObj.login(send_by, mail_pass) # 登錄驗證 smtpObj.sendmail(send_by, send_to.split(','), message.as_string()) # 發(fā)送 logger.info("郵箱驗證碼發(fā)送成功!") except Exception as e: logger.warning(e) """ qq 郵箱授權(quán)碼位于 qq 郵箱 app 的“設(shè)置”—“賬號”—“授權(quán)設(shè)置”—“第三方授權(quán)”中, 具體步驟包括:打開 qq 郵箱 app、點擊“我”、進入“設(shè)置”、選擇“賬號”、進入“授權(quán)設(shè)置”、 查看“第三方授權(quán)”,找到您需要查看授權(quán)碼的應(yīng)用,點擊右側(cè)的“查看授權(quán)”按鈕,即可獲取授權(quán)碼。 """ """ 郵件格式 email_config = { 'send_to': "", # 收件人郵箱,可以是列表 'content': "這是郵件內(nèi)容。", # 郵件內(nèi)容 'subject': "", # 郵件主題 'send_by': "", # 發(fā)件人郵箱 'mail_host': "smtp.qq.com", # SMTP服務(wù)器地址 'port': 465, # SMTP服務(wù)器端口 'mail_pass': "" # 授權(quán)密碼,非登錄密碼 } """ def send_emai_code(send_to: str): email_config = config.email_config # 生成驗證碼 verificate_code = get_str_code() # 獲取 send_to 郵箱地址的前3位和@符號前4位的內(nèi)容 formatted_email = send_to[0:3] + '...' + send_to[send_to.index('@') - 4:send_to.index('@')] email_config['send_to'] = send_to # 構(gòu)建格式化的郵件內(nèi)容 email_config['content'] = f"""【HXAutoTest】你正在登錄 {formatted_email}, 驗證碼:{verificate_code}。 提供給他人會導致賬號泄露,若非本人操作,請修改密碼!""" try: send_email(email_config) return verificate_code except Exception as e: logger.warning(f"發(fā)送驗證碼失?。篭n{e}") return ''
后端Redis緩存策略 ??
在郵箱登錄流程中,后端需要處理驗證碼的生成、發(fā)送和驗證。使用Redis作為緩存解決方案,可以有效地提高這一流程的效率。
驗證碼生成與發(fā)送
- 生成驗證碼:在用戶請求發(fā)送驗證碼時,后端生成一個隨機的驗證碼。
- 發(fā)送驗證碼:通過郵件服務(wù)將驗證碼發(fā)送到用戶郵箱。
- 緩存驗證碼:將驗證碼及其有效期存儲在Redis中,以鍵值對的形式,鍵為用戶郵箱,值為驗證碼。
驗證碼驗證
當用戶輸入驗證碼進行登錄時,后端需要:
- 查詢Redis:根據(jù)用戶郵箱查詢Redis中的緩存驗證碼。
- 驗證驗證碼:比對用戶輸入的驗證碼與Redis中的緩存值。
- 更新狀態(tài):如果驗證碼匹配,允許用戶登錄;否則,提示錯誤信息。
結(jié)語 ??
通過前端的郵箱格式校驗和后端的Redis緩存策略,我們可以構(gòu)建一個既高效又安全的郵箱登錄系統(tǒng)。這種方法不僅提升了用戶體驗,也增強了系統(tǒng)的安全性。隨著技術(shù)的發(fā)展,我們應(yīng)不斷探索和優(yōu)化用戶認證流程,以適應(yīng)不斷變化的網(wǎng)絡(luò)環(huán)境。
到此這篇關(guān)于Python 郵箱登錄驗證碼功能實現(xiàn)的文章就介紹到這了,更多相關(guān)Python 郵箱登錄驗證碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python elasticsearch環(huán)境搭建詳解
在本篇文章里小編給大家整理的是關(guān)于python elasticsearch環(huán)境搭建的相關(guān)知識點內(nèi)容,有需要的朋友們可以參考下。2019-09-09Python使用qrcode庫實現(xiàn)生成二維碼的操作指南
二維碼是一種廣泛使用的二維條碼,因其高效的數(shù)據(jù)存儲能力和易于掃描的特點,廣泛應(yīng)用于支付、身份驗證、營銷推廣等領(lǐng)域,Python qrcode 庫是一個生成二維碼的工具,它能夠幫助我們輕松地生成二維碼,在本文中,我們將深入解析 qrcode 庫的使用方法及其實際應(yīng)用2025-01-01python 讀取yaml文件的兩種方法(在unittest中使用)
這篇文章主要介紹了python 讀取yaml文件的兩種方法(在unittest中使用),幫助大家更好的理解和學習python,感興趣的朋友可以了解下2020-12-12一步步教你用python連接oracle數(shù)據(jù)庫
oracle作為最強大的數(shù)據(jù)庫,Python也提供了足夠的支持。不過與其他數(shù)據(jù)庫略有不同,下面這篇文章主要給大家介紹了關(guān)于如何使用python連接oracle數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下2023-04-04