Python 郵箱登錄驗證碼功能實現代碼
郵箱登錄:前端校驗與后端Redis緩存策略 ??
在構建Web平臺時,郵箱登錄功能是用戶認證的重要環(huán)節(jié)。本文將介紹一種結合前端校驗和后端Redis緩存的郵箱登錄實現邏輯,旨在提高安全性和效率。
前言 ??
隨著互聯(lián)網服務的多樣化,用戶登錄方式也在不斷演進。郵箱登錄因其便捷性和普及性,成為了許多Web平臺的首選認證方式。本文將探討在實現郵箱登錄過程中,如何通過前端校驗和后端Redis緩存策略,提高登錄流程的安全性和效率。
前端郵箱輸入 ???
注:代碼不是完整代碼 因為涉及到其他模塊的引用 這里只是提供一個實現思路 具體代碼要根據項目去更改
<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">
// 定義變量內容
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: 驗證碼應該設置過期
// 獲取郵箱驗證碼
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();
// 后端獲取菜單數據
await initBackEndControlRoutes();
// 前端獲取菜單數據
// await initFrontEndControlRoutes();
signInSuccess(false);
})
.catch((e) => {
console.log('錯誤信息: ', e)
state.loading.signIn = false;
})
};
// 登錄成功后的跳轉
const signInSuccess = (isNoPower) => {
if (isNoPower) {
ElMessage.warning('抱歉,您沒有登錄權限');
Session.clear();
} else {
// 初始化登錄成功時間問候語
let currentTimeInfo = currentTime.value;
// 登錄成功,跳到轉首頁
// 如果是復制粘貼的路徑,非首頁/登錄頁,那么登錄成功后重定向到對應的路徑中
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,防止第一次進入界面時出現短暫空白
NextLoading.start();
}
state.loading.signIn = false;
};
</script>后端郵箱驗證碼發(fā)送 ??
生成驗證碼:在用戶請求發(fā)送驗證碼時,后端生成一個隨機的驗證碼。
def get_str_code(length=4):
# 生成一個隨機的UUID
random_uuid = uuid.uuid4()
# 將UUID轉換為32位的十六進制字符串
code = random_uuid.hex
# 截取指定長度的字符串
return code[:length]發(fā)送驗證碼:通過郵件服務將驗證碼發(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']
# 構建郵件內容
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 郵箱授權碼位于 qq 郵箱 app 的“設置”—“賬號”—“授權設置”—“第三方授權”中,
具體步驟包括:打開 qq 郵箱 app、點擊“我”、進入“設置”、選擇“賬號”、進入“授權設置”、
查看“第三方授權”,找到您需要查看授權碼的應用,點擊右側的“查看授權”按鈕,即可獲取授權碼。
"""
""" 郵件格式
email_config = {
'send_to': "", # 收件人郵箱,可以是列表
'content': "這是郵件內容。", # 郵件內容
'subject': "", # 郵件主題
'send_by': "", # 發(fā)件人郵箱
'mail_host': "smtp.qq.com", # SMTP服務器地址
'port': 465, # SMTP服務器端口
'mail_pass': "" # 授權密碼,非登錄密碼
}
"""
def send_emai_code(send_to: str):
email_config = config.email_config
# 生成驗證碼
verificate_code = get_str_code()
# 獲取 send_to 郵箱地址的前3位和@符號前4位的內容
formatted_email = send_to[0:3] + '...' + send_to[send_to.index('@') - 4:send_to.index('@')]
email_config['send_to'] = send_to
# 構建格式化的郵件內容
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ā)送驗證碼:通過郵件服務將驗證碼發(fā)送到用戶郵箱。
- 緩存驗證碼:將驗證碼及其有效期存儲在Redis中,以鍵值對的形式,鍵為用戶郵箱,值為驗證碼。
驗證碼驗證
當用戶輸入驗證碼進行登錄時,后端需要:
- 查詢Redis:根據用戶郵箱查詢Redis中的緩存驗證碼。
- 驗證驗證碼:比對用戶輸入的驗證碼與Redis中的緩存值。
- 更新狀態(tài):如果驗證碼匹配,允許用戶登錄;否則,提示錯誤信息。
結語 ??
通過前端的郵箱格式校驗和后端的Redis緩存策略,我們可以構建一個既高效又安全的郵箱登錄系統(tǒng)。這種方法不僅提升了用戶體驗,也增強了系統(tǒng)的安全性。隨著技術的發(fā)展,我們應不斷探索和優(yōu)化用戶認證流程,以適應不斷變化的網絡環(huán)境。
到此這篇關于Python 郵箱登錄驗證碼功能實現的文章就介紹到這了,更多相關Python 郵箱登錄驗證碼內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python elasticsearch環(huán)境搭建詳解
在本篇文章里小編給大家整理的是關于python elasticsearch環(huán)境搭建的相關知識點內容,有需要的朋友們可以參考下。2019-09-09
python 讀取yaml文件的兩種方法(在unittest中使用)
這篇文章主要介紹了python 讀取yaml文件的兩種方法(在unittest中使用),幫助大家更好的理解和學習python,感興趣的朋友可以了解下2020-12-12

