登录支持用户选择邮箱或手机动态码并消除同步发信等待
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-09-18 20:57:46 +08:00
1 parent 04cc5774e0
commit 41593ee762
25 files changed
+1223 -207

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@ export function usePage() {
}
loading.value = true
try {
const res = await http.post("/api/v1/login", form)
const res = await http.post("/api/v1/login", form, { timeout: 4500 })
if (res.errorNo !== 0) {
ElMessage.error(res.errorMsg)
return
@@ -44,6 +44,27 @@
overflow-wrap: anywhere;
}
.verification-methods {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 16px;
}
.verification-methods .el-button {
flex: 1;
min-height: 48px;
margin: 0;
}
.verification-hint,
.verification-delivery {
color: var(--pm-text-secondary);
font-size: 14px;
line-height: 1.7;
margin-bottom: 20px;
}
.verification-input :deep(.el-input__wrapper) {
min-height: 48px;
border-radius: 12px;
@@ -104,4 +125,4 @@
flex-direction: column;
align-items: center;
}
}
}
@@ -7,11 +7,6 @@ import { useRouter } from "vue-router"
import { useGlobalStatusStore } from "@/stores/useGlobalStatusStore"
import { http } from "@/utils/axios"
import { getSafeLoginRedirect } from "@/utils/navigation.mjs"
import {
normalizeRequestOptions,
serializeCredential,
webAuthnSupported
} from "@/utils/webauthn"
export function usePage() {
const router = useRouter()
@@ -20,24 +15,71 @@ export function usePage() {
const code = ref("")
const loading = ref(false)
const resending = ref(false)
const webAuthnLoading = ref(false)
const method = ref("")
const retrySeconds = ref(0)
const remainingSeconds = ref(0)
const errorMessage = ref("")
let timer = null
let polling = false
let disposed = false
const expiresAt = computed(() => pending.value?.expiresAt || "")
const webAuthnAvailable = computed(() => webAuthnSupported())
const methods = computed(() => pending.value?.methods || [])
const sending = computed(() => pending.value?.deliveryStatus === "sending")
const deliveryMessage = computed(() => {
switch (pending.value?.deliveryStatus) {
case "sending": return "正在发送邮件,您可以等待,也可以切换到手机动态码。"
case "sent": return "收件服务器已接收邮件,请检查收件箱和垃圾邮件。"
case "failed": return pending.value?.deliveryError || "邮件发送失败,请稍后重试。"
default: return "点击发送验证码后,我们会向绑定邮箱发送邮件。"
}
})
const savePending = (data, id) => {
if (disposed || pending.value?.challengeId !== id) return
globalStatus.setPendingLogin({ ...data, redirect: pending.value.redirect })
updateRemaining()
}
const pollStatus = async () => {
if (polling || !sending.value || remainingSeconds.value <= 0) return
polling = true
const id = pending.value.challengeId
try {
const result = await http.post("/api/v1/security/login/status", {
id, account: pending.value.account
}, { timeout: 4500 })
if (result.errorNo !== 0) throw new Error(result.errorMsg || "无法查询发送状态")
savePending(result.data, id)
errorMessage.value = ""
} catch (error) {
if (!disposed) errorMessage.value = "发送状态暂时无法更新,请检查网络;无需重复发送。"
} finally {
polling = false
}
}
const chooseMethod = value => {
if (!methods.value.includes(value) || loading.value) return
method.value = value
code.value = ""
errorMessage.value = ""
}
const updateRemaining = () => {
const timestamp = Date.parse(expiresAt.value)
remainingSeconds.value = Number.isFinite(timestamp)
? Math.max(0, Math.ceil((timestamp - Date.now()) / 1000))
: 0
retrySeconds.value = Math.max(0, Math.ceil((Date.parse(pending.value?.retryAt) - Date.now()) / 1000)) || 0
}
const startTimer = () => {
updateRemaining()
timer = window.setInterval(updateRemaining, 1000)
timer = window.setInterval(() => {
updateRemaining()
pollStatus()
}, 1000)
}
const stopTimer = () => {
@@ -57,8 +99,10 @@ export function usePage() {
await goBackToLogin()
return
}
if (!code.value.trim()) {
ElMessage.warning("请输入邮箱验证码")
if (loading.value || !method.value) return
const pattern = method.value === "totp" ? /^\d{6}$/ : /^\d{8}$/
if (!pattern.test(code.value.trim())) {
ElMessage.warning(method.value === "totp" ? "请输入六位手机动态码" : "请输入八位邮箱验证码")
return
}
if (remainingSeconds.value <= 0) {
@@ -73,8 +117,9 @@ export function usePage() {
const response = await http.post("/api/v1/security/login/verify", {
id: pending.value.challengeId,
account: pending.value.account,
code: code.value.trim()
})
code: code.value.trim(),
method: method.value
}, { timeout: 4500 })
if (response.errorNo !== 0) {
throw new Error(response.errorMsg || "验证码验证失败")
}
@@ -91,75 +136,35 @@ export function usePage() {
}
const resendCode = async () => {
if (!pending.value?.challengeId || resending.value) {
if (!pending.value?.challengeId || resending.value || sending.value || retrySeconds.value > 0) {
return
}
resending.value = true
errorMessage.value = ""
try {
const id = pending.value.challengeId
const response = await http.post("/api/v1/security/login/resend", {
id: pending.value.challengeId,
id,
account: pending.value.account
})
}, { timeout: 4500 })
if (response.errorNo !== 0 || !response.data?.pending) {
throw new Error(response.errorMsg || "验证码发送失败")
}
globalStatus.setPendingLogin({
...response.data,
redirect: pending.value.redirect
})
savePending(response.data, id)
code.value = ""
ElMessage.success("验证码已重新发送")
stopTimer()
startTimer()
} catch (error) {
errorMessage.value = error?.message || "验证码发送失败,请稍后重试"
if (error?.code === 'ECONNABORTED' || error?.code === 'ERR_NETWORK') {
errorMessage.value = "发送请求未确认,正在查询状态,请勿重复点击。"
if (pending.value) pending.value.deliveryStatus = "sending"
} else {
errorMessage.value = error?.message || "验证码发送失败,请稍后重试"
}
ElMessage.error(errorMessage.value)
} finally {
resending.value = false
}
}
const verifyWithWebAuthn = async () => {
if (!webAuthnAvailable.value || webAuthnLoading.value) {
return
}
webAuthnLoading.value = true
errorMessage.value = ""
try {
const begin = await http.post("/api/v1/security/webauthn/login/begin", {
challenge_id: pending.value.challengeId,
account: pending.value.account
})
if (begin.errorNo !== 0) {
throw new Error(begin.errorMsg || "安全密钥登录不可用")
}
const credential = await navigator.credentials.get({
publicKey: normalizeRequestOptions(begin.data.options)
})
const finish = await http.post("/api/v1/security/webauthn/login/finish", {
challenge_id: pending.value.challengeId,
account: pending.value.account,
session_id: begin.data.session_id,
credential: serializeCredential(credential)
})
if (finish.errorNo !== 0) {
throw new Error(finish.errorMsg || "安全密钥验证失败")
}
const redirect = getSafeLoginRedirect(pending.value?.redirect)
globalStatus.clearPendingLogin()
globalStatus.setUser(finish.data, true)
await router.replace(redirect)
} catch (error) {
if (error?.name !== "NotAllowedError") {
errorMessage.value = error?.message || "安全密钥验证失败,请重试"
ElMessage.error(errorMessage.value)
}
} finally {
webAuthnLoading.value = false
}
}
onMounted(() => {
if (!pending.value?.challengeId) {
router.replace({ name: "login" })
@@ -168,20 +173,26 @@ export function usePage() {
startTimer()
})
onBeforeUnmount(stopTimer)
onBeforeUnmount(() => {
disposed = true
stopTimer()
})
return {
pending,
code,
loading,
resending,
webAuthnLoading,
method,
methods,
sending,
retrySeconds,
deliveryMessage,
chooseMethod,
remainingSeconds,
errorMessage,
webAuthnAvailable,
verifyCode,
resendCode,
verifyWithWebAuthn,
goBackToLogin
}
}
@@ -2,24 +2,53 @@
<AuthLayout
brand-caption="安全、简洁的邮件管理"
intro-title="完成安全验证"
intro-description="密码验证通过后,还需要确认已绑定的外部安全邮箱或安全密钥。"
intro-description="账号密码已通过验证。选择邮箱验证码或手机动态码,完成其中一种验证即可登录。"
>
<section class="verification-content">
<div class="verification-card">
<div class="verification-heading">
<span class="verification-eyebrow">登录保护</span>
<h2>输入邮箱验证码</h2>
<p>
验证码已发送至
<strong>{{ pending?.email || "已绑定邮箱" }}</strong>
</p>
<h2>选择验证方式</h2>
<p>当前账号:<strong>{{ pending?.account }}</strong></p>
</div>
<el-form class="verification-form" @submit.prevent="verifyCode">
<el-form-item label="邮箱验证码">
<div class="verification-methods">
<el-button
:type="method === 'email' ? 'primary' : 'default'"
:disabled="!methods.includes('email') || loading"
@click="chooseMethod('email')"
>邮箱验证码</el-button>
<el-button
:type="method === 'totp' ? 'primary' : 'default'"
:disabled="!methods.includes('totp') || loading"
@click="chooseMethod('totp')"
>手机动态码(TOTP)</el-button>
</div>
<p v-if="!methods.includes('totp')" class="verification-hint">
尚未启用手机动态码,可在登录后的安全中心自行开启。
</p>
<p v-if="!methods.includes('email')" class="verification-hint">
尚未绑定可用的安全邮箱,请使用手机动态码。
</p>
<div v-if="method === 'email'" class="verification-delivery" aria-live="polite">
<p>绑定邮箱:<strong>{{ pending?.email }}</strong></p>
<p>{{ deliveryMessage }}</p>
<el-button
:loading="resending"
:disabled="sending || retrySeconds > 0 || remainingSeconds <= 0"
@click="resendCode"
>{{ sending ? '正在发送' : retrySeconds > 0 ? `${retrySeconds} 秒后可重发` : '发送邮箱验证码' }}</el-button>
</div>
<p v-if="method === 'totp'" class="verification-hint">
打开已绑定的手机验证器,输入当前六位动态码。已使用的动态码请等待更新。
</p>
<el-form v-if="method" class="verification-form" @submit.prevent="verifyCode">
<el-form-item :label="method === 'totp' ? '六位手机动态码' : '八位邮箱验证码'">
<el-input
v-model="code"
maxlength="8"
:maxlength="method === 'totp' ? 6 : 8"
inputmode="numeric"
autocomplete="one-time-code"
placeholder="请输入验证码"
@@ -38,8 +67,8 @@
<p class="verification-expiry">
{{ remainingSeconds > 0
? `验证码将在 ${remainingSeconds} 秒后过期`
: "验证码已过期,请重新登录" }}
? `请在 ${remainingSeconds} 秒内完成登录验证`
: "登录验证已过期,请重新登录" }}
</p>
<el-button
@@ -47,41 +76,16 @@
size="large"
class="verification-submit"
:loading="loading"
:disabled="remainingSeconds <= 0"
:disabled="remainingSeconds <= 0 || (method === 'email' && pending?.deliveryStatus !== 'sent')"
@click="verifyCode"
>
验证并登录
</el-button>
<div class="verification-actions">
<el-button
link
type="primary"
:loading="resending"
:disabled="remainingSeconds > 540"
@click="resendCode"
>
重新发送验证码
</el-button>
<el-button link @click="goBackToLogin">返回登录</el-button>
</div>
</el-form>
<el-divider>或</el-divider>
<el-button
v-if="webAuthnAvailable"
plain
size="large"
class="webauthn-login-button"
:loading="webAuthnLoading"
@click="verifyWithWebAuthn"
>
使用安全密钥验证
</el-button>
<p v-else class="webauthn-unavailable">
当前浏览器不支持安全密钥验证,请使用邮箱验证码。
</p>
<div class="verification-actions">
<el-button link :disabled="loading" @click="goBackToLogin">返回登录</el-button>
</div>
</div>
</section>
</AuthLayout>
@@ -96,15 +100,18 @@ const {
code,
loading,
resending,
webAuthnLoading,
method,
methods,
sending,
retrySeconds,
deliveryMessage,
chooseMethod,
remainingSeconds,
errorMessage,
webAuthnAvailable,
verifyCode,
resendCode,
verifyWithWebAuthn,
goBackToLogin
} = usePage()
</script>
<style scoped src="./LoginVerification.css"></style>
<style scoped src="./LoginVerification.css"></style>
@@ -25,6 +25,7 @@ export function usePage() {
options.push({ value: 'recovery', label: '离线恢复码' })
}
options.push({ value: 'external-email', label: '外部安全邮箱' })
options.push({ value: 'totp', label: '手机动态码' })
options.push({ value: 'webauthn', label: '安全密钥' })
return options
})
@@ -110,6 +110,8 @@
<el-empty v-else v-loading="externalListLoading" description="暂无外部安全邮箱" />
</section>
<TOTPSettings v-if="selectedSection === 'totp'" />
<el-divider v-if="selectedSection === 'webauthn'" class="settings-divider" />
<el-alert
v-if="selectedSection === 'webauthn' && !webAuthnEnabled"
@@ -137,6 +139,7 @@
<script setup>
import { usePage } from './SecuritySettings.js'
import ProfileSettings from './ProfileSettings/ProfileSettings.vue'
import TOTPSettings from './TOTPSettings/TOTPSettings.vue'
import SettingsSubmenu from '../SettingsSubmenu/SettingsSubmenu.vue'
import GlobalSecurityPolicy from './GlobalSecurityPolicy/GlobalSecurityPolicy.vue'
import ExternalEmailBindingDialog from './ExternalEmailBindingDialog/ExternalEmailBindingDialog.vue'
@@ -0,0 +1,34 @@
.totp-settings {
max-width: 640px;
padding: 20px 0;
}
.totp-settings p {
color: var(--pm-text-secondary);
line-height: 1.7;
}
.totp-settings .el-alert {
margin-bottom: 16px;
}
.totp-enrollment img,
.totp-enrollment label,
.totp-enrollment code {
display: block;
margin: 12px 0;
}
.totp-enrollment code {
padding: 12px;
border: 1px solid var(--pm-border-color);
border-radius: 8px;
overflow-wrap: anywhere;
user-select: all;
}
.totp-actions {
display: flex;
gap: 12px;
margin-top: 16px;
}
@@ -0,0 +1,75 @@
import { onBeforeUnmount, onMounted, ref } from 'vue'
import QRCode from 'qrcode'
import { ElMessage } from 'element-plus'
import { http } from '@/utils/axios'
import { isRecentAuthenticationCancelled, requestWithRecentAuthentication } from '@/utils/recentAuthentication'
export function useTOTPSettings() {
const enabled = ref(false)
const ready = ref(false)
const busy = ref(false)
const enrollment = ref(null)
const qrCode = ref('')
const code = ref('')
const errorMessage = ref('')
let disposed = false
const clearEnrollment = () => {
enrollment.value = null
qrCode.value = ''
code.value = ''
}
const load = async () => {
const result = await http.get('/api/v1/security/totp', { timeout: 4500 })
if (result.errorNo !== 0) throw new Error(result.errorMsg || '无法读取动态码状态')
if (disposed) return
enabled.value = result.data.enabled
ready.value = true
}
const perform = async action => {
if (busy.value) return
if (['confirm', 'disable'].includes(action) && !/^\d{6}$/.test(code.value)) {
ElMessage.warning('请输入手机验证器生成的六位动态码')
return
}
busy.value = true
errorMessage.value = ''
try {
const result = await requestWithRecentAuthentication(() => http.post('/api/v1/security/totp', {
action, id: enrollment.value?.id, code: code.value
}, { timeout: 4500 }))
if (result.errorNo !== 0) throw new Error(result.errorMsg || '动态码设置失败')
if (disposed) return
if (action === 'begin') {
enrollment.value = result.data
// 二维码在浏览器本地生成,密钥不会发送给第三方服务。
qrCode.value = await QRCode.toDataURL(result.data.uri, { width: 240, margin: 2 })
} else {
clearEnrollment()
await load()
if (action !== 'cancel') ElMessage.success(action === 'confirm' ? '手机动态码已启用' : '手机动态码已关闭')
}
} catch (error) {
if (!disposed && !isRecentAuthenticationCancelled(error)) {
errorMessage.value = error?.message || '操作失败,请刷新状态后重试'
}
} finally {
busy.value = false
}
}
const refresh = async () => {
busy.value = true
errorMessage.value = ''
try { await load() } catch (error) { errorMessage.value = error.message } finally { busy.value = false }
}
onMounted(refresh)
onBeforeUnmount(() => {
disposed = true
clearEnrollment()
})
return { enabled, ready, busy, enrollment, qrCode, code, errorMessage, perform, refresh }
}
@@ -0,0 +1,45 @@
<template>
<section class="totp-settings" v-loading="busy">
<h3>手机动态码(TOTP)</h3>
<p>所有账号都可以自行选择是否开启。开启后,输入账号密码即可选择手机动态码或邮箱验证码登录。</p>
<el-alert v-if="errorMessage" :title="errorMessage" type="error" :closable="false" show-icon />
<el-button v-if="!ready" :disabled="busy" @click="refresh">重新读取状态</el-button>
<template v-else>
<el-tag :type="enabled ? 'success' : 'info'">{{ enabled ? '已启用' : '未启用' }}</el-tag>
<div v-if="enrollment" class="totp-enrollment">
<p>使用手机验证器扫描二维码,或手动输入下面的密钥。绑定申请十分钟内有效。</p>
<img v-if="qrCode" :src="qrCode" alt="手机验证器绑定二维码" width="240" height="240" />
<label>手动绑定密钥</label>
<code>{{ enrollment.secret }}</code>
<p>算法:SHA256;位数:6;周期:30 秒。请妥善保管密钥,勿分享给他人。</p>
<el-form @submit.prevent="perform('confirm')">
<el-form-item label="六位手机动态码">
<el-input v-model="code" maxlength="6" inputmode="numeric" autocomplete="one-time-code" placeholder="输入手机上当前显示的动态码" />
</el-form-item>
<div class="totp-actions">
<el-button type="primary" :disabled="busy" @click="perform('confirm')">确认启用</el-button>
<el-button :disabled="busy" @click="perform('cancel')">取消绑定</el-button>
</div>
</el-form>
</div>
<el-form v-else-if="enabled" class="totp-disable" @submit.prevent="perform('disable')">
<p>关闭前请输入当前动态码。刚绑定或已用于验证的动态码需要等待下一次更新。</p>
<el-form-item label="六位手机动态码">
<el-input v-model="code" maxlength="6" inputmode="numeric" autocomplete="one-time-code" placeholder="输入动态码以确认关闭" />
</el-form-item>
<el-button type="danger" plain :disabled="busy" @click="perform('disable')">关闭手机动态码</el-button>
</el-form>
<div v-else class="totp-actions">
<el-button type="primary" :disabled="busy" @click="perform('begin')">绑定手机验证器</el-button>
</div>
</template>
</section>
</template>
<script setup>
import { useTOTPSettings } from './TOTPSettings.js'
const { enabled, ready, busy, enrollment, qrCode, code, errorMessage, perform, refresh } = useTOTPSettings()
</script>
<style scoped src="./TOTPSettings.css"></style>