Python 郵箱登錄驗(yàn)證碼功能實(shí)現(xiàn)代碼
郵箱登錄:前端校驗(yàn)與后端Redis緩存策略 ??
在構(gòu)建Web平臺(tái)時(shí),郵箱登錄功能是用戶認(rèn)證的重要環(huán)節(jié)。本文將介紹一種結(jié)合前端校驗(yàn)和后端Redis緩存的郵箱登錄實(shí)現(xiàn)邏輯,旨在提高安全性和效率。
前言 ??
隨著互聯(lián)網(wǎng)服務(wù)的多樣化,用戶登錄方式也在不斷演進(jìn)。郵箱登錄因其便捷性和普及性,成為了許多Web平臺(tái)的首選認(rèn)證方式。本文將探討在實(shí)現(xiàn)郵箱登錄過程中,如何通過前端校驗(yàn)和后端Redis緩存策略,提高登錄流程的安全性和效率。
前端郵箱輸入 ???
注:代碼不是完整代碼 因?yàn)樯婕暗狡渌K的引用 這里只是提供一個(gè)實(shí)現(xiàn)思路 具體代碼要根據(jù)項(xiàng)目去更改
<template>
<el-form size="large" class="login-content-form" :model="state.ruleForm">
<el-form-item
class="login-animation1"
prop="email"
:rules="[
{ required: true, message: '請(qǐng)輸入郵箱地址', trigger: 'blur' },
{ type: 'email', message: '請(qǐng)輸入正確的郵箱地址', trigger: ['blur', 'change'] } ]" >
<el-input text placeholder="請(qǐng)輸入郵箱" 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="請(qǐng)輸入驗(yàn)證碼"
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,
},
});
// 時(shí)間獲取
const currentTime = computed(() => {
return formatAxis(new Date());
});
// TODO: 驗(yàn)證碼應(yīng)該設(shè)置過期
// 獲取郵箱驗(yàn)證碼
const get_email_code = async () => {
if (state.ruleForm.email.toLowerCase() === '') {
ElMessage.error('請(qǐng)重新輸入郵箱');
return
}
// 觸發(fā)按鈕倒計(jì)時(shí)
countDownFunction(120);
useUserApi().getCode({email: state.ruleForm.email})
.then(async res => {
state.email_code = res.data;
})
.catch((e) => {
console.log('錯(cuò)誤信息: ', 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('驗(yàn)證碼錯(cuò)誤,請(qǐng)重新輸入');
state.ruleForm.code = ''; // 清空輸入框
state.loading.signIn = false;
return
}
useUserApi().signIn({email: state.ruleForm.email})
.then(async res => {
// 存儲(chǔ)token
Session.set('token', res.data.token);
// 存儲(chǔ)用戶信息
await useUserInfo().setUserInfos();
// 后端獲取菜單數(shù)據(jù)
await initBackEndControlRoutes();
// 前端獲取菜單數(shù)據(jù)
// await initFrontEndControlRoutes();
signInSuccess(false);
})
.catch((e) => {
console.log('錯(cuò)誤信息: ', e)
state.loading.signIn = false;
})
};
// 登錄成功后的跳轉(zhuǎn)
const signInSuccess = (isNoPower) => {
if (isNoPower) {
ElMessage.warning('抱歉,您沒有登錄權(quán)限');
Session.clear();
} else {
// 初始化登錄成功時(shí)間問候語
let currentTimeInfo = currentTime.value;
// 登錄成功,跳到轉(zhuǎn)首頁
// 如果是復(fù)制粘貼的路徑,非首頁/登錄頁,那么登錄成功后重定向到對(duì)應(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,防止第一次進(jìn)入界面時(shí)出現(xiàn)短暫空白
NextLoading.start();
}
state.loading.signIn = false;
};
</script>后端郵箱驗(yàn)證碼發(fā)送 ??
生成驗(yàn)證碼:在用戶請(qǐng)求發(fā)送驗(yàn)證碼時(shí),后端生成一個(gè)隨機(jī)的驗(yàn)證碼。
def get_str_code(length=4):
# 生成一個(gè)隨機(jī)的UUID
random_uuid = uuid.uuid4()
# 將UUID轉(zhuǎn)換為32位的十六進(jìn)制字符串
code = random_uuid.hex
# 截取指定長度的字符串
return code[:length]發(fā)送驗(yàn)證碼:通過郵件服務(wù)將驗(yàn)證碼發(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) # 登錄驗(yàn)證
smtpObj.sendmail(send_by, send_to.split(','), message.as_string()) # 發(fā)送
logger.info("郵箱驗(yàn)證碼發(fā)送成功!")
except Exception as e:
logger.warning(e)
"""
qq 郵箱授權(quán)碼位于 qq 郵箱 app 的“設(shè)置”—“賬號(hào)”—“授權(quán)設(shè)置”—“第三方授權(quán)”中,
具體步驟包括:打開 qq 郵箱 app、點(diǎn)擊“我”、進(jìn)入“設(shè)置”、選擇“賬號(hào)”、進(jìn)入“授權(quán)設(shè)置”、
查看“第三方授權(quán)”,找到您需要查看授權(quán)碼的應(yīng)用,點(diǎn)擊右側(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
# 生成驗(yàn)證碼
verificate_code = get_str_code()
# 獲取 send_to 郵箱地址的前3位和@符號(hào)前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},
驗(yàn)證碼:{verificate_code}。
提供給他人會(huì)導(dǎo)致賬號(hào)泄露,若非本人操作,請(qǐng)修改密碼!"""
try:
send_email(email_config)
return verificate_code
except Exception as e:
logger.warning(f"發(fā)送驗(yàn)證碼失?。篭n{e}")
return ''后端Redis緩存策略 ??
在郵箱登錄流程中,后端需要處理驗(yàn)證碼的生成、發(fā)送和驗(yàn)證。使用Redis作為緩存解決方案,可以有效地提高這一流程的效率。
驗(yàn)證碼生成與發(fā)送
- 生成驗(yàn)證碼:在用戶請(qǐng)求發(fā)送驗(yàn)證碼時(shí),后端生成一個(gè)隨機(jī)的驗(yàn)證碼。
- 發(fā)送驗(yàn)證碼:通過郵件服務(wù)將驗(yàn)證碼發(fā)送到用戶郵箱。
- 緩存驗(yàn)證碼:將驗(yàn)證碼及其有效期存儲(chǔ)在Redis中,以鍵值對(duì)的形式,鍵為用戶郵箱,值為驗(yàn)證碼。
驗(yàn)證碼驗(yàn)證
當(dāng)用戶輸入驗(yàn)證碼進(jìn)行登錄時(shí),后端需要:
- 查詢Redis:根據(jù)用戶郵箱查詢Redis中的緩存驗(yàn)證碼。
- 驗(yàn)證驗(yàn)證碼:比對(duì)用戶輸入的驗(yàn)證碼與Redis中的緩存值。
- 更新狀態(tài):如果驗(yàn)證碼匹配,允許用戶登錄;否則,提示錯(cuò)誤信息。
結(jié)語 ??
通過前端的郵箱格式校驗(yàn)和后端的Redis緩存策略,我們可以構(gòu)建一個(gè)既高效又安全的郵箱登錄系統(tǒng)。這種方法不僅提升了用戶體驗(yàn),也增強(qiáng)了系統(tǒng)的安全性。隨著技術(shù)的發(fā)展,我們應(yīng)不斷探索和優(yōu)化用戶認(rèn)證流程,以適應(yīng)不斷變化的網(wǎng)絡(luò)環(huán)境。
到此這篇關(guān)于Python 郵箱登錄驗(yàn)證碼功能實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python 郵箱登錄驗(yàn)證碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python基于Django實(shí)現(xiàn)驗(yàn)證碼登錄功能
- python爬蟲模擬登錄之圖片驗(yàn)證碼實(shí)現(xiàn)詳解
- python網(wǎng)絡(luò)爬蟲之模擬登錄 自動(dòng)獲取cookie值 驗(yàn)證碼識(shí)別的具體實(shí)現(xiàn)
- 教你怎么用python批量登錄帶有驗(yàn)證碼的網(wǎng)站
- python 模擬網(wǎng)站登錄——滑塊驗(yàn)證碼的識(shí)別
- Python爬蟲爬取ts碎片視頻+驗(yàn)證碼登錄功能
- python3定位并識(shí)別圖片驗(yàn)證碼實(shí)現(xiàn)自動(dòng)登錄功能
- Python +Selenium解決圖片驗(yàn)證碼登錄或注冊(cè)問題(推薦)
相關(guān)文章
python elasticsearch環(huán)境搭建詳解
在本篇文章里小編給大家整理的是關(guān)于python elasticsearch環(huán)境搭建的相關(guān)知識(shí)點(diǎn)內(nèi)容,有需要的朋友們可以參考下。2019-09-09
Python 給屏幕打印信息加上顏色的實(shí)現(xiàn)方法
這篇文章主要介紹了Python 給屏幕打印信息加上顏色的實(shí)現(xiàn)方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04
Python使用qrcode庫實(shí)現(xiàn)生成二維碼的操作指南
二維碼是一種廣泛使用的二維條碼,因其高效的數(shù)據(jù)存儲(chǔ)能力和易于掃描的特點(diǎn),廣泛應(yīng)用于支付、身份驗(yàn)證、營銷推廣等領(lǐng)域,Python qrcode 庫是一個(gè)生成二維碼的工具,它能夠幫助我們輕松地生成二維碼,在本文中,我們將深入解析 qrcode 庫的使用方法及其實(shí)際應(yīng)用2025-01-01
python 讀取yaml文件的兩種方法(在unittest中使用)
這篇文章主要介紹了python 讀取yaml文件的兩種方法(在unittest中使用),幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2020-12-12
學(xué)習(xí)win32com操作word之Range精講
這篇文章主要為大家介紹了win32com操作word之Range精講學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
一步步教你用python連接oracle數(shù)據(jù)庫
oracle作為最強(qiáng)大的數(shù)據(jù)庫,Python也提供了足夠的支持。不過與其他數(shù)據(jù)庫略有不同,下面這篇文章主要給大家介紹了關(guān)于如何使用python連接oracle數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下2023-04-04

