mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 17:30:23 +08:00
fix(public): 修复用户可见性、额度、验证与 Codex 探测
This commit is contained in:
@@ -227,6 +227,8 @@
|
||||
:require-email-verification="requireEmailVerification"
|
||||
:email-configured="emailConfigured"
|
||||
:password-policy-level="passwordPolicyLevel"
|
||||
:turnstile-enabled="turnstileEnabled"
|
||||
:turnstile-site-key="turnstileSiteKey"
|
||||
@success="handleRegisterSuccess"
|
||||
@switch-to-login="handleSwitchToLogin"
|
||||
/>
|
||||
@@ -270,6 +272,8 @@ const showRegisterDialog = ref(false)
|
||||
const requireEmailVerification = ref(false)
|
||||
const emailConfigured = ref(true) // 邮箱服务是否已配置
|
||||
const passwordPolicyLevel = ref<PasswordPolicyLevel>('weak')
|
||||
const turnstileEnabled = ref(false)
|
||||
const turnstileSiteKey = ref<string | null>(null)
|
||||
const allowRegistration = ref(false) // 由系统配置控制,默认关闭
|
||||
|
||||
// LDAP authentication settings
|
||||
@@ -388,6 +392,8 @@ onMounted(async () => {
|
||||
requireEmailVerification.value = !!regSettings.require_email_verification
|
||||
emailConfigured.value = !!regSettings.email_configured
|
||||
passwordPolicyLevel.value = normalizePasswordPolicyLevel(regSettings.password_policy_level)
|
||||
turnstileEnabled.value = !!regSettings.turnstile_enabled
|
||||
turnstileSiteKey.value = regSettings.turnstile_site_key || null
|
||||
|
||||
localEnabled.value = authSettings.local_enabled
|
||||
ldapEnabled.value = authSettings.ldap_enabled
|
||||
@@ -413,6 +419,8 @@ onMounted(async () => {
|
||||
requireEmailVerification.value = false
|
||||
emailConfigured.value = false
|
||||
passwordPolicyLevel.value = 'weak'
|
||||
turnstileEnabled.value = false
|
||||
turnstileSiteKey.value = null
|
||||
localEnabled.value = true
|
||||
ldapEnabled.value = false
|
||||
ldapExclusive.value = false
|
||||
|
||||
@@ -55,6 +55,20 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="turnstileRequired && (!requireEmailVerification || !emailVerified)"
|
||||
class="space-y-2"
|
||||
>
|
||||
<Label>人机验证 <span class="text-destructive">*</span></Label>
|
||||
<TurnstileWidget
|
||||
ref="turnstileWidgetRef"
|
||||
v-model="turnstileToken"
|
||||
:site-key="turnstileSiteKey"
|
||||
:disabled="isLoading || isSendingCode"
|
||||
@error="handleTurnstileError"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Verification Code Section (仅当需要邮箱验证时显示) -->
|
||||
<div
|
||||
v-if="emailConfigured && requireEmailVerification"
|
||||
@@ -232,7 +246,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onUnmounted, nextTick } from 'vue'
|
||||
import { authApi } from '@/api/auth'
|
||||
import { authApi, type RegisterRequest } from '@/api/auth'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import {
|
||||
@@ -245,12 +259,15 @@ import { Dialog } from '@/components/ui'
|
||||
import Button from '@/components/ui/button.vue'
|
||||
import Input from '@/components/ui/input.vue'
|
||||
import Label from '@/components/ui/label.vue'
|
||||
import TurnstileWidget from './TurnstileWidget.vue'
|
||||
|
||||
interface Props {
|
||||
open?: boolean
|
||||
requireEmailVerification?: boolean
|
||||
emailConfigured?: boolean
|
||||
passwordPolicyLevel?: PasswordPolicyLevel
|
||||
turnstileEnabled?: boolean
|
||||
turnstileSiteKey?: string | null
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
@@ -263,7 +280,9 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
open: false,
|
||||
requireEmailVerification: false,
|
||||
emailConfigured: true,
|
||||
passwordPolicyLevel: 'weak'
|
||||
passwordPolicyLevel: 'weak',
|
||||
turnstileEnabled: false,
|
||||
turnstileSiteKey: null
|
||||
})
|
||||
|
||||
const emit = defineEmits<Emits>()
|
||||
@@ -379,11 +398,26 @@ const codeSentAt = ref<number | null>(null)
|
||||
const cooldownSeconds = ref(0)
|
||||
const expireMinutes = ref(5)
|
||||
const cooldownTimer = ref<number | null>(null)
|
||||
const turnstileToken = ref('')
|
||||
const turnstileWidgetRef = ref<InstanceType<typeof TurnstileWidget> | null>(null)
|
||||
|
||||
const turnstileSiteKey = computed(() => props.turnstileSiteKey || '')
|
||||
const turnstileRequired = computed(() => !!props.turnstileEnabled && !!turnstileSiteKey.value)
|
||||
|
||||
const resetTurnstile = () => {
|
||||
turnstileToken.value = ''
|
||||
turnstileWidgetRef.value?.reset()
|
||||
}
|
||||
|
||||
const handleTurnstileError = (message: string) => {
|
||||
showError(message, '人机验证失败')
|
||||
}
|
||||
|
||||
// Send code cooldown timer
|
||||
const canSendCode = computed(() => {
|
||||
if (!formData.value.email) return false
|
||||
if (cooldownSeconds.value > 0) return false
|
||||
if (turnstileRequired.value && !turnstileToken.value) return false
|
||||
return true
|
||||
})
|
||||
|
||||
@@ -391,6 +425,7 @@ const sendCodeButtonText = computed(() => {
|
||||
if (isSendingCode.value) return '发送中...'
|
||||
if (emailVerified.value) return '验证成功'
|
||||
if (cooldownSeconds.value > 0) return `${cooldownSeconds.value}秒后重试`
|
||||
if (turnstileRequired.value && !turnstileToken.value) return '请先完成人机验证'
|
||||
if (codeSentAt.value) return '重新发送验证码'
|
||||
return '发送验证码'
|
||||
})
|
||||
@@ -428,6 +463,8 @@ const canSubmit = computed(() => {
|
||||
if (!formData.value.email || !emailVerified.value) {
|
||||
return false
|
||||
}
|
||||
} else if (turnstileRequired.value && !turnstileToken.value) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check password match
|
||||
@@ -484,6 +521,7 @@ watch(
|
||||
cooldownTimer.value = null
|
||||
}
|
||||
codeDigits.value = ['', '', '', '', '', '']
|
||||
resetTurnstile()
|
||||
}
|
||||
|
||||
// 清除之前的定时器
|
||||
@@ -551,6 +589,7 @@ const resetForm = () => {
|
||||
isSendingCode.value = false
|
||||
codeSentAt.value = null
|
||||
cooldownSeconds.value = 0
|
||||
resetTurnstile()
|
||||
|
||||
// Reset password field nonce
|
||||
formNonce.value = createFormNonce()
|
||||
@@ -581,9 +620,13 @@ const handleSendCode = async () => {
|
||||
isSendingCode.value = true
|
||||
|
||||
try {
|
||||
const response = await authApi.sendVerificationCode(formData.value.email)
|
||||
const response = await authApi.sendVerificationCode(
|
||||
formData.value.email,
|
||||
turnstileRequired.value ? turnstileToken.value : undefined
|
||||
)
|
||||
|
||||
if (response.success) {
|
||||
resetTurnstile()
|
||||
codeSentAt.value = Date.now()
|
||||
if (response.expire_minutes) {
|
||||
expireMinutes.value = response.expire_minutes
|
||||
@@ -599,9 +642,11 @@ const handleSendCode = async () => {
|
||||
codeInputRefs.value[0]?.focus()
|
||||
})
|
||||
} else {
|
||||
resetTurnstile()
|
||||
showError(response.message || '请稍后重试', '发送失败')
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
resetTurnstile()
|
||||
showError(parseApiError(error, '网络错误,请重试'), '发送失败')
|
||||
} finally {
|
||||
isSendingCode.value = false
|
||||
@@ -657,13 +702,17 @@ const handleSubmit = async () => {
|
||||
showError('请先完成邮箱验证')
|
||||
return
|
||||
}
|
||||
if (!props.requireEmailVerification && turnstileRequired.value && !turnstileToken.value) {
|
||||
showError('请先完成人机验证')
|
||||
return
|
||||
}
|
||||
|
||||
isLoading.value = true
|
||||
loadingText.value = '注册中...'
|
||||
|
||||
try {
|
||||
// 构建请求数据:邮箱可选
|
||||
const registerData: { email?: string; username: string; password: string } = {
|
||||
const registerData: RegisterRequest = {
|
||||
username: formData.value.username,
|
||||
password: formData.value.password
|
||||
}
|
||||
@@ -671,6 +720,9 @@ const handleSubmit = async () => {
|
||||
if (formData.value.email && formData.value.email.trim()) {
|
||||
registerData.email = formData.value.email
|
||||
}
|
||||
if (!props.requireEmailVerification && turnstileRequired.value) {
|
||||
registerData.turnstile_token = turnstileToken.value
|
||||
}
|
||||
|
||||
const response = await authApi.register(registerData)
|
||||
|
||||
@@ -679,6 +731,7 @@ const handleSubmit = async () => {
|
||||
emit('success')
|
||||
isOpen.value = false
|
||||
} catch (error: unknown) {
|
||||
resetTurnstile()
|
||||
showError(parseApiError(error, '注册失败,请重试'), '注册失败')
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
|
||||
157
frontend/src/features/auth/components/TurnstileWidget.vue
Normal file
157
frontend/src/features/auth/components/TurnstileWidget.vue
Normal file
@@ -0,0 +1,157 @@
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<div
|
||||
ref="containerRef"
|
||||
class="min-h-[65px]"
|
||||
:class="disabled ? 'pointer-events-none opacity-60' : ''"
|
||||
/>
|
||||
<p
|
||||
v-if="errorMessage"
|
||||
class="text-xs text-destructive"
|
||||
>
|
||||
{{ errorMessage }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
|
||||
const TURNSTILE_SCRIPT_URL = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
|
||||
|
||||
let loadTurnstilePromise: Promise<void> | null = null
|
||||
|
||||
interface TurnstileApi {
|
||||
render: (container: HTMLElement, options: Record<string, unknown>) => string
|
||||
reset: (widgetId: string) => void
|
||||
remove: (widgetId: string) => void
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
turnstile?: TurnstileApi
|
||||
}
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue?: string
|
||||
siteKey: string
|
||||
disabled?: boolean
|
||||
}>(), {
|
||||
modelValue: '',
|
||||
disabled: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: string]
|
||||
error: [message: string]
|
||||
}>()
|
||||
|
||||
const containerRef = ref<HTMLElement | null>(null)
|
||||
const widgetId = ref<string | null>(null)
|
||||
const errorMessage = ref('')
|
||||
|
||||
function loadTurnstileScript(): Promise<void> {
|
||||
if (window.turnstile) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
if (loadTurnstilePromise) {
|
||||
return loadTurnstilePromise
|
||||
}
|
||||
|
||||
loadTurnstilePromise = new Promise((resolve, reject) => {
|
||||
const existing = document.querySelector<HTMLScriptElement>(
|
||||
`script[src="${TURNSTILE_SCRIPT_URL}"]`
|
||||
)
|
||||
if (existing) {
|
||||
existing.addEventListener('load', () => resolve(), { once: true })
|
||||
existing.addEventListener('error', () => {
|
||||
existing.remove()
|
||||
loadTurnstilePromise = null
|
||||
reject(new Error('turnstile script failed'))
|
||||
}, { once: true })
|
||||
return
|
||||
}
|
||||
|
||||
const script = document.createElement('script')
|
||||
script.src = TURNSTILE_SCRIPT_URL
|
||||
script.async = true
|
||||
script.defer = true
|
||||
script.onload = () => resolve()
|
||||
script.onerror = () => {
|
||||
script.remove()
|
||||
loadTurnstilePromise = null
|
||||
reject(new Error('turnstile script failed'))
|
||||
}
|
||||
document.head.appendChild(script)
|
||||
})
|
||||
|
||||
return loadTurnstilePromise
|
||||
}
|
||||
|
||||
function clearWidget() {
|
||||
if (widgetId.value && window.turnstile) {
|
||||
window.turnstile.remove(widgetId.value)
|
||||
}
|
||||
widgetId.value = null
|
||||
emit('update:modelValue', '')
|
||||
}
|
||||
|
||||
async function renderWidget() {
|
||||
if (!props.siteKey || !containerRef.value) return
|
||||
clearWidget()
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
await loadTurnstileScript()
|
||||
await nextTick()
|
||||
if (!window.turnstile || !containerRef.value) return
|
||||
widgetId.value = window.turnstile.render(containerRef.value, {
|
||||
sitekey: props.siteKey,
|
||||
callback: (token: string) => {
|
||||
errorMessage.value = ''
|
||||
emit('update:modelValue', token)
|
||||
},
|
||||
'expired-callback': () => {
|
||||
emit('update:modelValue', '')
|
||||
},
|
||||
'error-callback': () => {
|
||||
const message = '人机验证加载失败,请重试'
|
||||
errorMessage.value = message
|
||||
emit('update:modelValue', '')
|
||||
emit('error', message)
|
||||
},
|
||||
})
|
||||
} catch {
|
||||
const message = '人机验证加载失败,请重试'
|
||||
errorMessage.value = message
|
||||
emit('update:modelValue', '')
|
||||
emit('error', message)
|
||||
}
|
||||
}
|
||||
|
||||
function reset() {
|
||||
emit('update:modelValue', '')
|
||||
errorMessage.value = ''
|
||||
if (widgetId.value && window.turnstile) {
|
||||
window.turnstile.reset(widgetId.value)
|
||||
return
|
||||
}
|
||||
void renderWidget()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void renderWidget()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (widgetId.value && window.turnstile) {
|
||||
window.turnstile.remove(widgetId.value)
|
||||
}
|
||||
})
|
||||
|
||||
watch(() => props.siteKey, () => {
|
||||
void renderWidget()
|
||||
})
|
||||
|
||||
defineExpose({ reset })
|
||||
</script>
|
||||
@@ -0,0 +1,205 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createApp, defineComponent, h, nextTick, type App } from 'vue'
|
||||
|
||||
import RegisterDialog from '../RegisterDialog.vue'
|
||||
|
||||
const authApiMocks = vi.hoisted(() => ({
|
||||
sendVerificationCode: vi.fn(),
|
||||
getVerificationStatus: vi.fn(),
|
||||
verifyEmail: vi.fn(),
|
||||
register: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/auth', () => ({
|
||||
authApi: authApiMocks,
|
||||
}))
|
||||
|
||||
vi.mock('@/composables/useToast', () => ({
|
||||
useToast: () => ({
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/utils/errorParser', () => ({
|
||||
parseApiError: (_error: unknown, fallback: string) => fallback,
|
||||
}))
|
||||
|
||||
vi.mock('../TurnstileWidget.vue', () => ({
|
||||
default: defineComponent({
|
||||
name: 'TurnstileWidgetStub',
|
||||
props: {
|
||||
modelValue: { type: String, default: '' },
|
||||
siteKey: { type: String, required: true },
|
||||
},
|
||||
emits: ['update:modelValue'],
|
||||
setup(_props, { emit, expose }) {
|
||||
expose({ reset: vi.fn() })
|
||||
return () =>
|
||||
h('button', {
|
||||
type: 'button',
|
||||
'data-testid': 'turnstile-widget',
|
||||
onClick: () => emit('update:modelValue', 'turnstile-token-123'),
|
||||
}, 'Turnstile')
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui', async () => {
|
||||
const { defineComponent, h } = await import('vue')
|
||||
return {
|
||||
Dialog: defineComponent({
|
||||
name: 'DialogStub',
|
||||
props: { open: { type: Boolean, default: false } },
|
||||
emits: ['update:open'],
|
||||
setup(props, { slots }) {
|
||||
return () => props.open
|
||||
? h('div', [slots.default?.(), slots.footer?.()])
|
||||
: null
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/components/ui/button.vue', async () => {
|
||||
const { defineComponent, h } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'ButtonStub',
|
||||
props: {
|
||||
disabled: { type: Boolean, default: false },
|
||||
type: { type: String, default: 'button' },
|
||||
},
|
||||
emits: ['click'],
|
||||
setup(props, { attrs, emit, slots }) {
|
||||
return () => h('button', {
|
||||
...attrs,
|
||||
type: props.type,
|
||||
disabled: props.disabled,
|
||||
onClick: (event: MouseEvent) => emit('click', event),
|
||||
}, slots.default?.())
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/components/ui/input.vue', async () => {
|
||||
const { defineComponent, h } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'InputStub',
|
||||
props: {
|
||||
modelValue: { type: [String, Number], default: '' },
|
||||
disabled: { type: Boolean, default: false },
|
||||
type: { type: String, default: 'text' },
|
||||
id: { type: String, default: undefined },
|
||||
},
|
||||
emits: ['update:modelValue'],
|
||||
setup(props, { attrs, emit }) {
|
||||
return () => h('input', {
|
||||
...attrs,
|
||||
id: props.id,
|
||||
type: props.type,
|
||||
disabled: props.disabled,
|
||||
value: props.modelValue,
|
||||
onInput: (event: Event) => emit('update:modelValue', (event.target as HTMLInputElement).value),
|
||||
})
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/components/ui/label.vue', async () => {
|
||||
const { defineComponent, h } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'LabelStub',
|
||||
setup(_props, { attrs, slots }) {
|
||||
return () => h('label', attrs, slots.default?.())
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
const mountedApps: Array<{ app: App, root: HTMLElement }> = []
|
||||
|
||||
function mountRegisterDialog() {
|
||||
const root = document.createElement('div')
|
||||
document.body.appendChild(root)
|
||||
const app = createApp(RegisterDialog, {
|
||||
open: true,
|
||||
requireEmailVerification: true,
|
||||
emailConfigured: true,
|
||||
turnstileEnabled: true,
|
||||
turnstileSiteKey: 'site-key-123',
|
||||
'onUpdate:open': vi.fn(),
|
||||
})
|
||||
app.mount(root)
|
||||
mountedApps.push({ app, root })
|
||||
return root
|
||||
}
|
||||
|
||||
async function settle() {
|
||||
for (let index = 0; index < 4; index += 1) {
|
||||
await Promise.resolve()
|
||||
await nextTick()
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
authApiMocks.sendVerificationCode.mockReset()
|
||||
authApiMocks.getVerificationStatus.mockReset()
|
||||
authApiMocks.verifyEmail.mockReset()
|
||||
authApiMocks.register.mockReset()
|
||||
authApiMocks.getVerificationStatus.mockResolvedValue({
|
||||
has_pending_code: false,
|
||||
is_verified: false,
|
||||
cooldown_remaining: null,
|
||||
code_expires_in: null,
|
||||
})
|
||||
authApiMocks.sendVerificationCode.mockResolvedValue({
|
||||
success: true,
|
||||
message: 'ok',
|
||||
expire_minutes: 5,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const { app, root } of mountedApps.splice(0)) {
|
||||
app.unmount()
|
||||
root.remove()
|
||||
}
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
describe('RegisterDialog Turnstile verification flow', () => {
|
||||
it('shows Turnstile before sending code and includes the token in the request', async () => {
|
||||
const root = mountRegisterDialog()
|
||||
await settle()
|
||||
|
||||
expect(root.textContent).toContain('Turnstile')
|
||||
const emailInput = root.querySelector('#reg-email') as HTMLInputElement
|
||||
emailInput.value = 'alice@example.com'
|
||||
emailInput.dispatchEvent(new Event('input'))
|
||||
await settle()
|
||||
|
||||
const sendButtonBeforeToken = Array.from(root.querySelectorAll('button'))
|
||||
.find((button) => button.textContent?.includes('请先完成人机验证')) as HTMLButtonElement
|
||||
expect(sendButtonBeforeToken.disabled).toBe(true)
|
||||
|
||||
const turnstileButton = root.querySelector('[data-testid="turnstile-widget"]') as HTMLButtonElement
|
||||
turnstileButton.click()
|
||||
await settle()
|
||||
|
||||
const sendButton = Array.from(root.querySelectorAll('button'))
|
||||
.find((button) => button.textContent?.includes('发送验证码')) as HTMLButtonElement
|
||||
expect(sendButton.disabled).toBe(false)
|
||||
sendButton.click()
|
||||
await settle()
|
||||
|
||||
expect(authApiMocks.sendVerificationCode).toHaveBeenCalledWith(
|
||||
'alice@example.com',
|
||||
'turnstile-token-123'
|
||||
)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user