feat: complete email binding and pending oauth verification flows
This commit is contained in:
@@ -449,6 +449,16 @@ export async function sendVerifyCode(
|
||||
return data
|
||||
}
|
||||
|
||||
export async function sendPendingOAuthVerifyCode(
|
||||
request: SendVerifyCodeRequest
|
||||
): Promise<SendVerifyCodeResponse> {
|
||||
const { data } = await apiClient.post<SendVerifyCodeResponse>(
|
||||
'/auth/oauth/pending/send-verify-code',
|
||||
request
|
||||
)
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate promo code response
|
||||
*/
|
||||
@@ -638,6 +648,7 @@ export const authAPI = {
|
||||
clearAuthToken,
|
||||
getPublicSettings,
|
||||
sendVerifyCode,
|
||||
sendPendingOAuthVerifyCode,
|
||||
validatePromoCode,
|
||||
validateInvitationCode,
|
||||
forgotPassword,
|
||||
|
||||
@@ -89,6 +89,19 @@ export async function toggleNotifyEmail(email: string, disabled: boolean): Promi
|
||||
return data
|
||||
}
|
||||
|
||||
export async function sendEmailBindingCode(email: string): Promise<void> {
|
||||
await apiClient.post('/user/account-bindings/email/send-code', { email })
|
||||
}
|
||||
|
||||
export async function bindEmailIdentity(payload: {
|
||||
email: string
|
||||
verify_code: string
|
||||
password: string
|
||||
}): Promise<User> {
|
||||
const { data } = await apiClient.post<User>('/user/account-bindings/email', payload)
|
||||
return data
|
||||
}
|
||||
|
||||
export type BindableOAuthProvider = Exclude<UserAuthProvider, 'email'>
|
||||
|
||||
interface BuildOAuthBindingStartURLOptions {
|
||||
@@ -158,6 +171,8 @@ export const userAPI = {
|
||||
verifyNotifyEmail,
|
||||
removeNotifyEmail,
|
||||
toggleNotifyEmail,
|
||||
sendEmailBindingCode,
|
||||
bindEmailIdentity,
|
||||
buildOAuthBindingStartURL,
|
||||
startOAuthBinding
|
||||
}
|
||||
|
||||
@@ -58,11 +58,20 @@
|
||||
<p v-else class="text-xs text-gray-500 dark:text-dark-400">
|
||||
{{ t('auth.verificationCodeHint') }}
|
||||
</p>
|
||||
<input
|
||||
v-if="invitationCodeEnabled"
|
||||
v-model="invitationCode"
|
||||
:data-testid="`${testIdPrefix}-create-account-invitation-code`"
|
||||
type="text"
|
||||
class="input w-full"
|
||||
:placeholder="t('auth.invitationCodePlaceholder')"
|
||||
:disabled="isSubmitting"
|
||||
/>
|
||||
<button
|
||||
:data-testid="`${testIdPrefix}-create-account-submit`"
|
||||
type="button"
|
||||
class="btn btn-primary w-full"
|
||||
:disabled="isSubmitting || !email.trim() || password.length < 6"
|
||||
:disabled="isSubmitting || !email.trim() || password.length < 6 || (invitationCodeEnabled && !invitationCode.trim())"
|
||||
@click="handleSubmit"
|
||||
>
|
||||
{{ isSubmitting ? t('common.processing') : 'Create account' }}
|
||||
@@ -92,12 +101,13 @@
|
||||
import { onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import TurnstileWidget from '@/components/TurnstileWidget.vue'
|
||||
import { getPublicSettings, sendVerifyCode } from '@/api/auth'
|
||||
import { getPublicSettings, sendPendingOAuthVerifyCode } from '@/api/auth'
|
||||
|
||||
export type PendingOAuthCreateAccountPayload = {
|
||||
email: string
|
||||
password: string
|
||||
verifyCode: string
|
||||
invitationCode?: string
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -117,10 +127,12 @@ const { t } = useI18n()
|
||||
const email = ref('')
|
||||
const password = ref('')
|
||||
const verifyCode = ref('')
|
||||
const invitationCode = ref('')
|
||||
const isSendingCode = ref(false)
|
||||
const sendCodeError = ref('')
|
||||
const sendCodeSuccess = ref(false)
|
||||
const countdown = ref(0)
|
||||
const invitationCodeEnabled = ref(false)
|
||||
const turnstileEnabled = ref(false)
|
||||
const turnstileSiteKey = ref('')
|
||||
const turnstileToken = ref('')
|
||||
@@ -203,7 +215,7 @@ async function handleSendCode() {
|
||||
sendCodeSuccess.value = false
|
||||
|
||||
try {
|
||||
const response = await sendVerifyCode({
|
||||
const response = await sendPendingOAuthVerifyCode({
|
||||
email: trimmedEmail,
|
||||
turnstile_token: turnstileEnabled.value ? turnstileToken.value : undefined
|
||||
})
|
||||
@@ -228,7 +240,8 @@ function handleSubmit() {
|
||||
emit('submit', {
|
||||
email: trimmedEmail,
|
||||
password: password.value,
|
||||
verifyCode: verifyCode.value.trim()
|
||||
verifyCode: verifyCode.value.trim(),
|
||||
invitationCode: invitationCode.value.trim() || undefined
|
||||
})
|
||||
}
|
||||
|
||||
@@ -239,9 +252,11 @@ function emitSwitchToBind() {
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const settings = await getPublicSettings()
|
||||
invitationCodeEnabled.value = settings.invitation_code_enabled === true
|
||||
turnstileEnabled.value = settings.turnstile_enabled === true
|
||||
turnstileSiteKey.value = settings.turnstile_site_key || ''
|
||||
} catch {
|
||||
invitationCodeEnabled.value = false
|
||||
turnstileEnabled.value = false
|
||||
turnstileSiteKey.value = ''
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { flushPromises, mount } from '@vue/test-utils'
|
||||
import PendingOAuthCreateAccountForm from '../PendingOAuthCreateAccountForm.vue'
|
||||
|
||||
const sendVerifyCode = vi.fn()
|
||||
const sendPendingOAuthVerifyCode = vi.fn()
|
||||
const getPublicSettings = vi.fn()
|
||||
|
||||
vi.mock('vue-i18n', async () => {
|
||||
@@ -21,6 +22,7 @@ vi.mock('@/api/auth', async () => {
|
||||
return {
|
||||
...actual,
|
||||
sendVerifyCode: (...args: any[]) => sendVerifyCode(...args),
|
||||
sendPendingOAuthVerifyCode: (...args: any[]) => sendPendingOAuthVerifyCode(...args),
|
||||
getPublicSettings: (...args: any[]) => getPublicSettings(...args)
|
||||
}
|
||||
})
|
||||
@@ -28,6 +30,7 @@ vi.mock('@/api/auth', async () => {
|
||||
describe('PendingOAuthCreateAccountForm', () => {
|
||||
beforeEach(() => {
|
||||
sendVerifyCode.mockReset()
|
||||
sendPendingOAuthVerifyCode.mockReset()
|
||||
getPublicSettings.mockReset()
|
||||
getPublicSettings.mockResolvedValue({
|
||||
turnstile_enabled: false,
|
||||
@@ -61,8 +64,42 @@ describe('PendingOAuthCreateAccountForm', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('shows and emits invitation code when invitation-only signup is enabled', async () => {
|
||||
getPublicSettings.mockResolvedValue({
|
||||
invitation_code_enabled: true,
|
||||
turnstile_enabled: false,
|
||||
turnstile_site_key: ''
|
||||
})
|
||||
|
||||
const wrapper = mount(PendingOAuthCreateAccountForm, {
|
||||
props: {
|
||||
providerName: 'LinuxDo',
|
||||
testIdPrefix: 'linuxdo',
|
||||
initialEmail: 'prefill@example.com',
|
||||
isSubmitting: false
|
||||
}
|
||||
})
|
||||
|
||||
await flushPromises()
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-password"]').setValue('secret-123')
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-verify-code"]').setValue('246810')
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-invitation-code"]').setValue(' INVITE123 ')
|
||||
await wrapper.get('form').trigger('submit.prevent')
|
||||
|
||||
expect(wrapper.emitted('submit')).toEqual([
|
||||
[
|
||||
{
|
||||
email: 'prefill@example.com',
|
||||
password: 'secret-123',
|
||||
verifyCode: '246810',
|
||||
invitationCode: 'INVITE123'
|
||||
}
|
||||
]
|
||||
])
|
||||
})
|
||||
|
||||
it('sends a verify code for the trimmed email value', async () => {
|
||||
sendVerifyCode.mockResolvedValue({
|
||||
sendPendingOAuthVerifyCode.mockResolvedValue({
|
||||
message: 'sent',
|
||||
countdown: 60
|
||||
})
|
||||
@@ -80,7 +117,7 @@ describe('PendingOAuthCreateAccountForm', () => {
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-send-code"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(sendVerifyCode).toHaveBeenCalledWith({
|
||||
expect(sendPendingOAuthVerifyCode).toHaveBeenCalledWith({
|
||||
email: 'user@example.com'
|
||||
})
|
||||
})
|
||||
@@ -90,7 +127,7 @@ describe('PendingOAuthCreateAccountForm', () => {
|
||||
turnstile_enabled: true,
|
||||
turnstile_site_key: 'site-key'
|
||||
})
|
||||
sendVerifyCode.mockResolvedValue({
|
||||
sendPendingOAuthVerifyCode.mockResolvedValue({
|
||||
message: 'sent',
|
||||
countdown: 60
|
||||
})
|
||||
@@ -120,7 +157,7 @@ describe('PendingOAuthCreateAccountForm', () => {
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-send-code"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(sendVerifyCode).toHaveBeenCalledWith({
|
||||
expect(sendPendingOAuthVerifyCode).toHaveBeenCalledWith({
|
||||
email: 'user@example.com',
|
||||
turnstile_token: 'turnstile-token'
|
||||
})
|
||||
|
||||
@@ -13,35 +13,96 @@
|
||||
<div
|
||||
v-for="item in providerItems"
|
||||
:key="item.provider"
|
||||
class="flex items-center justify-between gap-3 rounded-xl bg-white/80 px-3 py-2.5 dark:bg-dark-800/70"
|
||||
class="rounded-xl bg-white/80 px-3 py-3 dark:bg-dark-800/70"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{{ item.label }}
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{{ item.label }}
|
||||
</div>
|
||||
<span
|
||||
:data-testid="`profile-binding-${item.provider}-status`"
|
||||
:class="['badge', item.bound ? 'badge-success' : 'badge-gray']"
|
||||
>
|
||||
{{
|
||||
item.bound
|
||||
? t('profile.authBindings.status.bound')
|
||||
: t('profile.authBindings.status.notBound')
|
||||
}}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="item.provider === 'email' && !item.bound"
|
||||
class="mt-3 grid gap-2 sm:grid-cols-[minmax(0,1.4fr)_auto]"
|
||||
>
|
||||
<input
|
||||
v-model.trim="emailBindingForm.email"
|
||||
data-testid="profile-binding-email-input"
|
||||
type="email"
|
||||
class="input"
|
||||
:placeholder="t('profile.authBindings.emailPlaceholder')"
|
||||
:disabled="isSendingEmailCode || isBindingEmail"
|
||||
/>
|
||||
<button
|
||||
data-testid="profile-binding-email-send-code"
|
||||
type="button"
|
||||
class="btn btn-secondary btn-sm"
|
||||
:disabled="isSendingEmailCode || isBindingEmail"
|
||||
@click="sendEmailCode"
|
||||
>
|
||||
{{
|
||||
isSendingEmailCode
|
||||
? t('common.loading')
|
||||
: t('profile.authBindings.sendCodeAction')
|
||||
}}
|
||||
</button>
|
||||
<input
|
||||
v-model.trim="emailBindingForm.verifyCode"
|
||||
data-testid="profile-binding-email-code-input"
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
maxlength="6"
|
||||
class="input"
|
||||
:placeholder="t('profile.authBindings.codePlaceholder')"
|
||||
:disabled="isBindingEmail"
|
||||
/>
|
||||
<input
|
||||
v-model="emailBindingForm.password"
|
||||
data-testid="profile-binding-email-password-input"
|
||||
type="password"
|
||||
class="input"
|
||||
:placeholder="t('profile.authBindings.passwordPlaceholder')"
|
||||
:disabled="isBindingEmail"
|
||||
/>
|
||||
<button
|
||||
data-testid="profile-binding-email-submit"
|
||||
type="button"
|
||||
class="btn btn-primary btn-sm sm:col-span-2"
|
||||
:disabled="isBindingEmail"
|
||||
@click="bindEmail"
|
||||
>
|
||||
{{
|
||||
isBindingEmail
|
||||
? t('common.loading')
|
||||
: t('profile.authBindings.confirmEmailBindAction')
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<span
|
||||
:data-testid="`profile-binding-${item.provider}-status`"
|
||||
:class="['badge', item.bound ? 'badge-success' : 'badge-gray']"
|
||||
>
|
||||
{{
|
||||
item.bound
|
||||
? t('profile.authBindings.status.bound')
|
||||
: t('profile.authBindings.status.notBound')
|
||||
}}
|
||||
</span>
|
||||
|
||||
<button
|
||||
v-if="item.canBind"
|
||||
:data-testid="`profile-binding-${item.provider}-action`"
|
||||
type="button"
|
||||
class="btn btn-secondary btn-sm"
|
||||
@click="startBinding(item.provider)"
|
||||
>
|
||||
{{ t('profile.authBindings.bindAction', { providerName: item.label }) }}
|
||||
</button>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<button
|
||||
v-if="item.canBind"
|
||||
:data-testid="`profile-binding-${item.provider}-action`"
|
||||
type="button"
|
||||
class="btn btn-secondary btn-sm"
|
||||
@click="startBinding(item.provider)"
|
||||
>
|
||||
{{ t('profile.authBindings.bindAction', { providerName: item.label }) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -49,7 +110,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRoute } from 'vue-router'
|
||||
import {
|
||||
@@ -57,8 +118,8 @@ import {
|
||||
resolveWeChatOAuthStartStrict,
|
||||
type WeChatOAuthPublicSettings,
|
||||
} from '@/api/auth'
|
||||
import { startOAuthBinding } from '@/api/user'
|
||||
import { useAppStore } from '@/stores'
|
||||
import { bindEmailIdentity, sendEmailBindingCode, startOAuthBinding } from '@/api/user'
|
||||
import { useAppStore, useAuthStore } from '@/stores'
|
||||
import type { User, UserAuthBindingStatus, UserAuthProvider } from '@/types'
|
||||
|
||||
const props = withDefaults(
|
||||
@@ -84,6 +145,32 @@ const props = withDefaults(
|
||||
const { t } = useI18n()
|
||||
const route = useRoute()
|
||||
const appStore = useAppStore()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const localUser = ref<User | null>(null)
|
||||
const isSendingEmailCode = ref(false)
|
||||
const isBindingEmail = ref(false)
|
||||
const emailBindingForm = reactive({
|
||||
email: '',
|
||||
verifyCode: '',
|
||||
password: '',
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.user,
|
||||
(user) => {
|
||||
localUser.value = null
|
||||
if (!user || getBindingStatusForUser(user, 'email')) {
|
||||
return
|
||||
}
|
||||
if (typeof user.email === 'string' && !user.email.endsWith('.invalid')) {
|
||||
emailBindingForm.email = user.email
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
const currentUser = computed(() => localUser.value ?? props.user)
|
||||
|
||||
const wechatOAuthSettings = computed<WeChatOAuthPublicSettings | null>(() => {
|
||||
if (hasExplicitWeChatOAuthCapabilities(appStore.cachedPublicSettings)) {
|
||||
@@ -117,20 +204,20 @@ function normalizeBindingStatus(binding: boolean | UserAuthBindingStatus | undef
|
||||
}
|
||||
|
||||
function getBindingStatus(provider: UserAuthProvider): boolean {
|
||||
const currentUser = props.user
|
||||
return getBindingStatusForUser(currentUser.value, provider)
|
||||
}
|
||||
|
||||
function getBindingStatusForUser(user: User | null | undefined, provider: UserAuthProvider): boolean {
|
||||
if (provider === 'email') {
|
||||
return typeof currentUser?.email_bound === 'boolean'
|
||||
? currentUser.email_bound
|
||||
: Boolean(currentUser?.email)
|
||||
return typeof user?.email_bound === 'boolean' ? user.email_bound : Boolean(user?.email)
|
||||
}
|
||||
|
||||
const directFlag = currentUser?.[`${provider}_bound` as keyof User]
|
||||
const directFlag = user?.[`${provider}_bound` as keyof User]
|
||||
if (typeof directFlag === 'boolean') {
|
||||
return directFlag
|
||||
}
|
||||
|
||||
const nested = currentUser?.auth_bindings?.[provider] ?? currentUser?.identity_bindings?.[provider]
|
||||
const nested = user?.auth_bindings?.[provider] ?? user?.identity_bindings?.[provider]
|
||||
const normalized = normalizeBindingStatus(nested)
|
||||
return normalized ?? false
|
||||
}
|
||||
@@ -171,4 +258,72 @@ function startBinding(provider: UserAuthProvider): void {
|
||||
wechatOAuthSettings: provider === 'wechat' ? wechatOAuthSettings.value : null,
|
||||
})
|
||||
}
|
||||
|
||||
function applyUpdatedUser(user: User): void {
|
||||
localUser.value = user
|
||||
authStore.user = user
|
||||
}
|
||||
|
||||
function validateEmailBindingForm(requireCode: boolean): boolean {
|
||||
if (!emailBindingForm.email) {
|
||||
appStore.showError(t('auth.emailRequired'))
|
||||
return false
|
||||
}
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailBindingForm.email)) {
|
||||
appStore.showError(t('auth.invalidEmail'))
|
||||
return false
|
||||
}
|
||||
if (requireCode && !emailBindingForm.verifyCode) {
|
||||
appStore.showError(t('auth.codeRequired'))
|
||||
return false
|
||||
}
|
||||
if (requireCode && !emailBindingForm.password) {
|
||||
appStore.showError(t('auth.passwordRequired'))
|
||||
return false
|
||||
}
|
||||
if (requireCode && emailBindingForm.password.length < 6) {
|
||||
appStore.showError(t('auth.passwordMinLength'))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
async function sendEmailCode(): Promise<void> {
|
||||
if (!validateEmailBindingForm(false)) {
|
||||
return
|
||||
}
|
||||
|
||||
isSendingEmailCode.value = true
|
||||
try {
|
||||
await sendEmailBindingCode(emailBindingForm.email)
|
||||
appStore.showSuccess(t('profile.authBindings.codeSentTo', { email: emailBindingForm.email }))
|
||||
} catch (error) {
|
||||
appStore.showError((error as { message?: string }).message || t('auth.sendCodeFailed'))
|
||||
} finally {
|
||||
isSendingEmailCode.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function bindEmail(): Promise<void> {
|
||||
if (!validateEmailBindingForm(true)) {
|
||||
return
|
||||
}
|
||||
|
||||
isBindingEmail.value = true
|
||||
try {
|
||||
const user = await bindEmailIdentity({
|
||||
email: emailBindingForm.email,
|
||||
verify_code: emailBindingForm.verifyCode,
|
||||
password: emailBindingForm.password,
|
||||
})
|
||||
applyUpdatedUser(user)
|
||||
emailBindingForm.verifyCode = ''
|
||||
emailBindingForm.password = ''
|
||||
appStore.showSuccess(t('profile.authBindings.bindSuccess'))
|
||||
} catch (error) {
|
||||
appStore.showError((error as { message?: string }).message || t('common.tryAgain'))
|
||||
} finally {
|
||||
isBindingEmail.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { mount } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import ProfileIdentityBindingsSection from '@/components/user/profile/ProfileIdentityBindingsSection.vue'
|
||||
import { useAppStore } from '@/stores'
|
||||
import { useAppStore, useAuthStore } from '@/stores'
|
||||
import type { User } from '@/types'
|
||||
|
||||
const routeState = vi.hoisted(() => ({
|
||||
@@ -15,10 +15,24 @@ const locationState = vi.hoisted(() => ({
|
||||
|
||||
let pinia: ReturnType<typeof createPinia>
|
||||
|
||||
const userApiMocks = vi.hoisted(() => ({
|
||||
sendEmailBindingCode: vi.fn(),
|
||||
bindEmailIdentity: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('vue-router', () => ({
|
||||
useRoute: () => routeState,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/user', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/api/user')>()
|
||||
return {
|
||||
...actual,
|
||||
sendEmailBindingCode: (...args: any[]) => userApiMocks.sendEmailBindingCode(...args),
|
||||
bindEmailIdentity: (...args: any[]) => userApiMocks.bindEmailIdentity(...args),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('vue-i18n', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('vue-i18n')>()
|
||||
return {
|
||||
@@ -34,6 +48,13 @@ vi.mock('vue-i18n', async (importOriginal) => {
|
||||
if (key === 'profile.authBindings.providers.wechat') return 'WeChat'
|
||||
if (key === 'profile.authBindings.providers.oidc') return params?.providerName || 'OIDC'
|
||||
if (key === 'profile.authBindings.bindAction') return `Bind ${params?.providerName || ''}`.trim()
|
||||
if (key === 'profile.authBindings.emailPlaceholder') return 'Email address'
|
||||
if (key === 'profile.authBindings.codePlaceholder') return 'Verification code'
|
||||
if (key === 'profile.authBindings.passwordPlaceholder') return 'Set password'
|
||||
if (key === 'profile.authBindings.sendCodeAction') return 'Send code'
|
||||
if (key === 'profile.authBindings.confirmEmailBindAction') return 'Bind email'
|
||||
if (key === 'profile.authBindings.codeSentTo') return `Code sent to ${params?.email || ''}`.trim()
|
||||
if (key === 'profile.authBindings.bindSuccess') return 'Bind success'
|
||||
return key
|
||||
},
|
||||
}),
|
||||
@@ -76,6 +97,8 @@ describe('ProfileIdentityBindingsSection', () => {
|
||||
const appStore = useAppStore()
|
||||
appStore.cachedPublicSettings = null
|
||||
appStore.publicSettingsLoaded = false
|
||||
userApiMocks.sendEmailBindingCode.mockReset()
|
||||
userApiMocks.bindEmailIdentity.mockReset()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -224,4 +247,58 @@ describe('ProfileIdentityBindingsSection', () => {
|
||||
|
||||
expect(wrapper.find('[data-testid="profile-binding-wechat-action"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('sends email verification code and binds email from the profile card', async () => {
|
||||
userApiMocks.sendEmailBindingCode.mockResolvedValue(undefined)
|
||||
userApiMocks.bindEmailIdentity.mockResolvedValue(
|
||||
createUser({
|
||||
email: 'bound@example.com',
|
||||
email_bound: true,
|
||||
auth_bindings: {
|
||||
email: { bound: true },
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
const appStore = useAppStore()
|
||||
const authStore = useAuthStore()
|
||||
authStore.user = createUser({
|
||||
email: 'legacy-user@linuxdo-connect.invalid',
|
||||
email_bound: false,
|
||||
auth_bindings: {
|
||||
email: { bound: false },
|
||||
},
|
||||
})
|
||||
const showSuccessSpy = vi.spyOn(appStore, 'showSuccess')
|
||||
|
||||
const wrapper = mount(ProfileIdentityBindingsSection, {
|
||||
global: {
|
||||
plugins: [pinia],
|
||||
},
|
||||
props: {
|
||||
user: authStore.user,
|
||||
linuxdoEnabled: false,
|
||||
oidcEnabled: false,
|
||||
wechatEnabled: false,
|
||||
},
|
||||
})
|
||||
|
||||
await wrapper.get('[data-testid="profile-binding-email-input"]').setValue('bound@example.com')
|
||||
await wrapper.get('[data-testid="profile-binding-email-send-code"]').trigger('click')
|
||||
|
||||
expect(userApiMocks.sendEmailBindingCode).toHaveBeenCalledWith('bound@example.com')
|
||||
expect(showSuccessSpy).toHaveBeenCalledWith('Code sent to bound@example.com')
|
||||
|
||||
await wrapper.get('[data-testid="profile-binding-email-code-input"]').setValue('123456')
|
||||
await wrapper.get('[data-testid="profile-binding-email-password-input"]').setValue('new-password')
|
||||
await wrapper.get('[data-testid="profile-binding-email-submit"]').trigger('click')
|
||||
|
||||
expect(userApiMocks.bindEmailIdentity).toHaveBeenCalledWith({
|
||||
email: 'bound@example.com',
|
||||
verify_code: '123456',
|
||||
password: 'new-password',
|
||||
})
|
||||
expect(wrapper.get('[data-testid="profile-binding-email-status"]').text()).toBe('Bound')
|
||||
expect(authStore.user?.email).toBe('bound@example.com')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -964,6 +964,12 @@ export default {
|
||||
description: 'View current bindings and connect another provider to this account.',
|
||||
bindAction: 'Bind {providerName}',
|
||||
bindSuccess: 'Account linked successfully',
|
||||
emailPlaceholder: 'Enter email address',
|
||||
codePlaceholder: 'Enter verification code',
|
||||
passwordPlaceholder: 'Set a login password',
|
||||
sendCodeAction: 'Send code',
|
||||
confirmEmailBindAction: 'Bind email',
|
||||
codeSentTo: 'Code sent to {email}',
|
||||
status: {
|
||||
bound: 'Bound',
|
||||
notBound: 'Not bound',
|
||||
|
||||
@@ -968,6 +968,12 @@ export default {
|
||||
description: '查看当前绑定状态,并将更多第三方登录方式关联到这个账号。',
|
||||
bindAction: '绑定 {providerName}',
|
||||
bindSuccess: '账号绑定成功',
|
||||
emailPlaceholder: '输入邮箱地址',
|
||||
codePlaceholder: '输入验证码',
|
||||
passwordPlaceholder: '设置登录密码',
|
||||
sendCodeAction: '发送验证码',
|
||||
confirmEmailBindAction: '绑定邮箱',
|
||||
codeSentTo: '验证码已发送到 {email}',
|
||||
status: {
|
||||
bound: '已绑定',
|
||||
notBound: '未绑定',
|
||||
|
||||
@@ -118,6 +118,8 @@ export interface RegisterRequest {
|
||||
export interface SendVerifyCodeRequest {
|
||||
email: string
|
||||
turnstile_token?: string
|
||||
pending_auth_token?: string
|
||||
pending_oauth_token?: string
|
||||
}
|
||||
|
||||
export interface SendVerifyCodeResponse {
|
||||
|
||||
@@ -176,7 +176,12 @@ import { AuthLayout } from '@/components/layout'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import TurnstileWidget from '@/components/TurnstileWidget.vue'
|
||||
import { useAuthStore, useAppStore } from '@/stores'
|
||||
import { persistOAuthTokenContext, getPublicSettings, sendVerifyCode } from '@/api/auth'
|
||||
import {
|
||||
persistOAuthTokenContext,
|
||||
getPublicSettings,
|
||||
sendPendingOAuthVerifyCode,
|
||||
sendVerifyCode,
|
||||
} from '@/api/auth'
|
||||
import { apiClient } from '@/api/client'
|
||||
import { buildAuthErrorMessage } from '@/utils/authError'
|
||||
import {
|
||||
@@ -355,18 +360,21 @@ async function sendCode(): Promise<void> {
|
||||
errorMessage.value = ''
|
||||
|
||||
try {
|
||||
if (!isRegistrationEmailSuffixAllowed(email.value, registrationEmailSuffixWhitelist.value)) {
|
||||
if (!pendingAuthToken.value && !isRegistrationEmailSuffixAllowed(email.value, registrationEmailSuffixWhitelist.value)) {
|
||||
errorMessage.value = buildEmailSuffixNotAllowedMessage()
|
||||
appStore.showError(errorMessage.value)
|
||||
return
|
||||
}
|
||||
|
||||
const response = await sendVerifyCode({
|
||||
const requestPayload = {
|
||||
email: email.value,
|
||||
[pendingAuthTokenField.value]: pendingAuthToken.value || undefined,
|
||||
// 优先使用重发时新获取的 token(因为初始 token 可能已被使用)
|
||||
turnstile_token: resendTurnstileToken.value || initialTurnstileToken.value || undefined
|
||||
} as Parameters<typeof sendVerifyCode>[0])
|
||||
} as Parameters<typeof sendVerifyCode>[0]
|
||||
const response = pendingAuthToken.value
|
||||
? await sendPendingOAuthVerifyCode(requestPayload)
|
||||
: await sendVerifyCode(requestPayload)
|
||||
|
||||
codeSent.value = true
|
||||
startCountdown(response.countdown)
|
||||
|
||||
@@ -444,6 +444,28 @@ function getRequestErrorMessage(error: unknown, fallback: string): string {
|
||||
return err.response?.data?.detail || err.response?.data?.message || err.message || fallback
|
||||
}
|
||||
|
||||
function isCreateAccountRecoveryError(error: unknown): boolean {
|
||||
const data = (error as {
|
||||
response?: {
|
||||
data?: {
|
||||
reason?: string
|
||||
error?: string
|
||||
code?: string
|
||||
step?: string
|
||||
intent?: string
|
||||
}
|
||||
}
|
||||
}).response?.data
|
||||
const states = [data?.reason, data?.error, data?.code, data?.step, data?.intent]
|
||||
.map(value => value?.trim().toLowerCase())
|
||||
.filter((value): value is string => Boolean(value))
|
||||
|
||||
return states.includes('email_exists') ||
|
||||
states.includes('bind_login_required') ||
|
||||
states.includes('bind_login') ||
|
||||
states.includes('adopt_existing_user_by_email')
|
||||
}
|
||||
|
||||
async function finalizeCompletion(completion: PendingOAuthExchangeResponse, redirect: string) {
|
||||
if (getOAuthCompletionKind(completion) === 'bind') {
|
||||
const bindRedirect = sanitizeRedirectPath(completion.redirect || '/profile')
|
||||
@@ -540,10 +562,15 @@ async function handleCreateAccount(payload: PendingOAuthCreateAccountPayload) {
|
||||
email: payload.email,
|
||||
password: payload.password,
|
||||
verify_code: payload.verifyCode || undefined,
|
||||
invitation_code: payload.invitationCode || undefined,
|
||||
...serializeAdoptionDecision(currentAdoptionDecision())
|
||||
})
|
||||
await finalizePendingAccountResponse(data)
|
||||
} catch (e: unknown) {
|
||||
if (isCreateAccountRecoveryError(e)) {
|
||||
switchToBindLoginMode(payload.email)
|
||||
return
|
||||
}
|
||||
accountActionError.value = getRequestErrorMessage(e, t('auth.loginFailed'))
|
||||
} finally {
|
||||
isSubmitting.value = false
|
||||
|
||||
@@ -488,6 +488,28 @@ function getRequestErrorMessage(error: unknown, fallback: string): string {
|
||||
return err.response?.data?.detail || err.response?.data?.message || err.message || fallback
|
||||
}
|
||||
|
||||
function isCreateAccountRecoveryError(error: unknown): boolean {
|
||||
const data = (error as {
|
||||
response?: {
|
||||
data?: {
|
||||
reason?: string
|
||||
error?: string
|
||||
code?: string
|
||||
step?: string
|
||||
intent?: string
|
||||
}
|
||||
}
|
||||
}).response?.data
|
||||
const states = [data?.reason, data?.error, data?.code, data?.step, data?.intent]
|
||||
.map(value => value?.trim().toLowerCase())
|
||||
.filter((value): value is string => Boolean(value))
|
||||
|
||||
return states.includes('email_exists') ||
|
||||
states.includes('bind_login_required') ||
|
||||
states.includes('bind_login') ||
|
||||
states.includes('adopt_existing_user_by_email')
|
||||
}
|
||||
|
||||
async function finalizeCompletion(completion: PendingOAuthExchangeResponse, redirect: string) {
|
||||
if (getOAuthCompletionKind(completion) === 'bind') {
|
||||
const bindRedirect = sanitizeRedirectPath(completion.redirect || '/profile')
|
||||
@@ -584,10 +606,15 @@ async function handleCreateAccount(payload: PendingOAuthCreateAccountPayload) {
|
||||
email: payload.email,
|
||||
password: payload.password,
|
||||
verify_code: payload.verifyCode || undefined,
|
||||
invitation_code: payload.invitationCode || undefined,
|
||||
...serializeAdoptionDecision(currentAdoptionDecision())
|
||||
})
|
||||
await finalizePendingAccountResponse(data)
|
||||
} catch (e: unknown) {
|
||||
if (isCreateAccountRecoveryError(e)) {
|
||||
switchToBindLoginMode(payload.email)
|
||||
return
|
||||
}
|
||||
accountActionError.value = getRequestErrorMessage(e, t('auth.loginFailed'))
|
||||
} finally {
|
||||
isSubmitting.value = false
|
||||
|
||||
@@ -647,6 +647,28 @@ function getRequestErrorMessage(error: unknown, fallback: string): string {
|
||||
return err.response?.data?.detail || err.response?.data?.message || err.message || fallback
|
||||
}
|
||||
|
||||
function isCreateAccountRecoveryError(error: unknown): boolean {
|
||||
const data = (error as {
|
||||
response?: {
|
||||
data?: {
|
||||
reason?: string
|
||||
error?: string
|
||||
code?: string
|
||||
step?: string
|
||||
intent?: string
|
||||
}
|
||||
}
|
||||
}).response?.data
|
||||
const states = [data?.reason, data?.error, data?.code, data?.step, data?.intent]
|
||||
.map(value => value?.trim().toLowerCase())
|
||||
.filter((value): value is string => Boolean(value))
|
||||
|
||||
return states.includes('email_exists') ||
|
||||
states.includes('bind_login_required') ||
|
||||
states.includes('bind_login') ||
|
||||
states.includes('adopt_existing_user_by_email')
|
||||
}
|
||||
|
||||
async function finalizeCompletion(completion: PendingOAuthExchangeResponse, redirect: string) {
|
||||
if (getOAuthCompletionKind(completion) === 'bind') {
|
||||
const bindRedirect = sanitizeRedirectPath(completion.redirect || '/profile')
|
||||
@@ -739,10 +761,15 @@ async function handleCreateAccount(payload: PendingOAuthCreateAccountPayload) {
|
||||
email: payload.email,
|
||||
password: payload.password,
|
||||
verify_code: payload.verifyCode || undefined,
|
||||
invitation_code: payload.invitationCode || undefined,
|
||||
...serializeAdoptionDecision(currentAdoptionDecision())
|
||||
})
|
||||
await finalizePendingAccountResponse(data)
|
||||
} catch (e: unknown) {
|
||||
if (isCreateAccountRecoveryError(e)) {
|
||||
switchToBindLoginMode(payload.email)
|
||||
return
|
||||
}
|
||||
accountActionError.value = getRequestErrorMessage(e, t('auth.loginFailed'))
|
||||
} finally {
|
||||
isSubmitting.value = false
|
||||
|
||||
@@ -11,6 +11,7 @@ const {
|
||||
clearPendingAuthSessionMock,
|
||||
getPublicSettingsMock,
|
||||
sendVerifyCodeMock,
|
||||
sendPendingOAuthVerifyCodeMock,
|
||||
persistOAuthTokenContextMock,
|
||||
apiClientPostMock,
|
||||
authStoreState,
|
||||
@@ -23,6 +24,7 @@ const {
|
||||
clearPendingAuthSessionMock: vi.fn(),
|
||||
getPublicSettingsMock: vi.fn(),
|
||||
sendVerifyCodeMock: vi.fn(),
|
||||
sendPendingOAuthVerifyCodeMock: vi.fn(),
|
||||
persistOAuthTokenContextMock: vi.fn(),
|
||||
apiClientPostMock: vi.fn(),
|
||||
authStoreState: {
|
||||
@@ -80,6 +82,7 @@ vi.mock('@/api/auth', async () => {
|
||||
...actual,
|
||||
getPublicSettings: (...args: any[]) => getPublicSettingsMock(...args),
|
||||
sendVerifyCode: (...args: any[]) => sendVerifyCodeMock(...args),
|
||||
sendPendingOAuthVerifyCode: (...args: any[]) => sendPendingOAuthVerifyCodeMock(...args),
|
||||
persistOAuthTokenContext: (...args: any[]) => persistOAuthTokenContextMock(...args),
|
||||
}
|
||||
})
|
||||
@@ -100,6 +103,7 @@ describe('EmailVerifyView', () => {
|
||||
clearPendingAuthSessionMock.mockReset()
|
||||
getPublicSettingsMock.mockReset()
|
||||
sendVerifyCodeMock.mockReset()
|
||||
sendPendingOAuthVerifyCodeMock.mockReset()
|
||||
persistOAuthTokenContextMock.mockReset()
|
||||
apiClientPostMock.mockReset()
|
||||
authStoreState.pendingAuthSession = null
|
||||
@@ -112,9 +116,86 @@ describe('EmailVerifyView', () => {
|
||||
registration_email_suffix_whitelist: [],
|
||||
})
|
||||
sendVerifyCodeMock.mockResolvedValue({ countdown: 60 })
|
||||
sendPendingOAuthVerifyCodeMock.mockResolvedValue({ countdown: 60 })
|
||||
setTokenMock.mockResolvedValue({})
|
||||
})
|
||||
|
||||
it('uses the pending oauth verify-code endpoint when register data carries a pending auth session', async () => {
|
||||
authStoreState.pendingAuthSession = {
|
||||
token: 'pending-token-1',
|
||||
token_field: 'pending_auth_token',
|
||||
provider: 'wechat',
|
||||
redirect: '/profile',
|
||||
}
|
||||
sessionStorage.setItem(
|
||||
'register_data',
|
||||
JSON.stringify({
|
||||
email: 'fresh@example.com',
|
||||
password: 'secret-123',
|
||||
})
|
||||
)
|
||||
|
||||
mount(EmailVerifyView, {
|
||||
global: {
|
||||
stubs: {
|
||||
AuthLayout: { template: '<div><slot /><slot name="footer" /></div>' },
|
||||
Icon: true,
|
||||
TurnstileWidget: true,
|
||||
transition: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await flushPromises()
|
||||
|
||||
expect(sendPendingOAuthVerifyCodeMock).toHaveBeenCalledWith({
|
||||
email: 'fresh@example.com',
|
||||
pending_auth_token: 'pending-token-1',
|
||||
})
|
||||
expect(sendVerifyCodeMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('skips the registration email suffix whitelist for pending oauth verification', async () => {
|
||||
authStoreState.pendingAuthSession = {
|
||||
token: 'pending-token-2',
|
||||
token_field: 'pending_auth_token',
|
||||
provider: 'oidc',
|
||||
redirect: '/profile',
|
||||
}
|
||||
getPublicSettingsMock.mockResolvedValue({
|
||||
turnstile_enabled: false,
|
||||
turnstile_site_key: '',
|
||||
site_name: 'Sub2API',
|
||||
registration_email_suffix_whitelist: ['allowed.com'],
|
||||
})
|
||||
sessionStorage.setItem(
|
||||
'register_data',
|
||||
JSON.stringify({
|
||||
email: 'fresh@example.com',
|
||||
password: 'secret-123',
|
||||
})
|
||||
)
|
||||
|
||||
mount(EmailVerifyView, {
|
||||
global: {
|
||||
stubs: {
|
||||
AuthLayout: { template: '<div><slot /><slot name="footer" /></div>' },
|
||||
Icon: true,
|
||||
TurnstileWidget: true,
|
||||
transition: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await flushPromises()
|
||||
|
||||
expect(sendPendingOAuthVerifyCodeMock).toHaveBeenCalledWith({
|
||||
email: 'fresh@example.com',
|
||||
pending_auth_token: 'pending-token-2',
|
||||
})
|
||||
expect(showErrorMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('submits pending auth account creation when session storage has no pending metadata but auth store does', async () => {
|
||||
authStoreState.pendingAuthSession = {
|
||||
token: 'pending-token-1',
|
||||
|
||||
@@ -15,6 +15,7 @@ const getPublicSettings = vi.fn()
|
||||
const login2FA = vi.fn()
|
||||
const apiClientPost = vi.fn()
|
||||
const sendVerifyCode = vi.fn()
|
||||
const sendPendingOAuthVerifyCode = vi.fn()
|
||||
|
||||
vi.mock('vue-router', () => ({
|
||||
useRoute: () => ({
|
||||
@@ -61,7 +62,8 @@ vi.mock('@/api/auth', async () => {
|
||||
completeLinuxDoOAuthRegistration: (...args: any[]) => completeLinuxDoOAuthRegistration(...args),
|
||||
getPublicSettings: (...args: any[]) => getPublicSettings(...args),
|
||||
login2FA: (...args: any[]) => login2FA(...args),
|
||||
sendVerifyCode: (...args: any[]) => sendVerifyCode(...args)
|
||||
sendVerifyCode: (...args: any[]) => sendVerifyCode(...args),
|
||||
sendPendingOAuthVerifyCode: (...args: any[]) => sendPendingOAuthVerifyCode(...args)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -79,6 +81,7 @@ describe('LinuxDoCallbackView', () => {
|
||||
login2FA.mockReset()
|
||||
apiClientPost.mockReset()
|
||||
sendVerifyCode.mockReset()
|
||||
sendPendingOAuthVerifyCode.mockReset()
|
||||
getPublicSettings.mockResolvedValue({
|
||||
turnstile_enabled: false,
|
||||
turnstile_site_key: ''
|
||||
@@ -334,6 +337,11 @@ describe('LinuxDoCallbackView', () => {
|
||||
})
|
||||
|
||||
it('collects email, password, and verify code for pending oauth account creation and submits adoption decisions', async () => {
|
||||
getPublicSettings.mockResolvedValue({
|
||||
invitation_code_enabled: true,
|
||||
turnstile_enabled: false,
|
||||
turnstile_site_key: ''
|
||||
})
|
||||
exchangePendingOAuthCompletion.mockResolvedValue({
|
||||
error: 'email_required',
|
||||
redirect: '/welcome',
|
||||
@@ -370,6 +378,7 @@ describe('LinuxDoCallbackView', () => {
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-email"]').setValue(' new@example.com ')
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-password"]').setValue('secret-123')
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-verify-code"]').setValue('246810')
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-invitation-code"]').setValue(' INVITE123 ')
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-submit"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
@@ -377,6 +386,7 @@ describe('LinuxDoCallbackView', () => {
|
||||
email: 'new@example.com',
|
||||
password: 'secret-123',
|
||||
verify_code: '246810',
|
||||
invitation_code: 'INVITE123',
|
||||
adopt_display_name: true,
|
||||
adopt_avatar: false
|
||||
})
|
||||
@@ -384,12 +394,48 @@ describe('LinuxDoCallbackView', () => {
|
||||
expect(replace).toHaveBeenCalledWith('/welcome')
|
||||
})
|
||||
|
||||
it('switches to bind-login when create-account returns EMAIL_EXISTS', async () => {
|
||||
exchangePendingOAuthCompletion.mockResolvedValue({
|
||||
error: 'email_required',
|
||||
redirect: '/welcome'
|
||||
})
|
||||
apiClientPost.mockRejectedValue({
|
||||
response: {
|
||||
data: {
|
||||
reason: 'EMAIL_EXISTS',
|
||||
message: 'email already exists'
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const wrapper = mount(LinuxDoCallbackView, {
|
||||
global: {
|
||||
stubs: {
|
||||
AuthLayout: { template: '<div><slot /></div>' },
|
||||
Icon: true,
|
||||
RouterLink: { template: '<a><slot /></a>' },
|
||||
transition: false
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
await flushPromises()
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-email"]').setValue('existing@example.com')
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-password"]').setValue('secret-123')
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-submit"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect((wrapper.get('[data-testid="linuxdo-bind-login-email"]').element as HTMLInputElement).value).toBe(
|
||||
'existing@example.com'
|
||||
)
|
||||
})
|
||||
|
||||
it('sends a verify code for pending oauth account creation', async () => {
|
||||
exchangePendingOAuthCompletion.mockResolvedValue({
|
||||
error: 'email_required',
|
||||
redirect: '/welcome'
|
||||
})
|
||||
sendVerifyCode.mockResolvedValue({
|
||||
sendPendingOAuthVerifyCode.mockResolvedValue({
|
||||
message: 'sent',
|
||||
countdown: 60
|
||||
})
|
||||
@@ -411,7 +457,7 @@ describe('LinuxDoCallbackView', () => {
|
||||
await wrapper.get('[data-testid="linuxdo-create-account-send-code"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(sendVerifyCode).toHaveBeenCalledWith({
|
||||
expect(sendPendingOAuthVerifyCode).toHaveBeenCalledWith({
|
||||
email: 'new@example.com'
|
||||
})
|
||||
})
|
||||
|
||||
@@ -15,6 +15,7 @@ const getPublicSettings = vi.fn()
|
||||
const login2FA = vi.fn()
|
||||
const apiClientPost = vi.fn()
|
||||
const sendVerifyCode = vi.fn()
|
||||
const sendPendingOAuthVerifyCode = vi.fn()
|
||||
|
||||
vi.mock('vue-router', () => ({
|
||||
useRoute: () => ({
|
||||
@@ -66,7 +67,8 @@ vi.mock('@/api/auth', async () => {
|
||||
completeOIDCOAuthRegistration: (...args: any[]) => completeOIDCOAuthRegistration(...args),
|
||||
getPublicSettings: (...args: any[]) => getPublicSettings(...args),
|
||||
login2FA: (...args: any[]) => login2FA(...args),
|
||||
sendVerifyCode: (...args: any[]) => sendVerifyCode(...args)
|
||||
sendVerifyCode: (...args: any[]) => sendVerifyCode(...args),
|
||||
sendPendingOAuthVerifyCode: (...args: any[]) => sendPendingOAuthVerifyCode(...args)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -84,6 +86,7 @@ describe('OidcCallbackView', () => {
|
||||
login2FA.mockReset()
|
||||
apiClientPost.mockReset()
|
||||
sendVerifyCode.mockReset()
|
||||
sendPendingOAuthVerifyCode.mockReset()
|
||||
getPublicSettings.mockResolvedValue({
|
||||
oidc_oauth_provider_name: 'ExampleID',
|
||||
turnstile_enabled: false,
|
||||
@@ -312,6 +315,12 @@ describe('OidcCallbackView', () => {
|
||||
})
|
||||
|
||||
it('collects email, password, and verify code for pending oauth account creation and submits adoption decisions', async () => {
|
||||
getPublicSettings.mockResolvedValue({
|
||||
oidc_oauth_provider_name: 'ExampleID',
|
||||
invitation_code_enabled: true,
|
||||
turnstile_enabled: false,
|
||||
turnstile_site_key: ''
|
||||
})
|
||||
exchangePendingOAuthCompletion.mockResolvedValue({
|
||||
error: 'email_required',
|
||||
redirect: '/welcome',
|
||||
@@ -348,6 +357,7 @@ describe('OidcCallbackView', () => {
|
||||
await wrapper.get('[data-testid="oidc-create-account-email"]').setValue(' new@example.com ')
|
||||
await wrapper.get('[data-testid="oidc-create-account-password"]').setValue('secret-123')
|
||||
await wrapper.get('[data-testid="oidc-create-account-verify-code"]').setValue('246810')
|
||||
await wrapper.get('[data-testid="oidc-create-account-invitation-code"]').setValue(' INVITE123 ')
|
||||
await wrapper.get('[data-testid="oidc-create-account-submit"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
@@ -355,6 +365,7 @@ describe('OidcCallbackView', () => {
|
||||
email: 'new@example.com',
|
||||
password: 'secret-123',
|
||||
verify_code: '246810',
|
||||
invitation_code: 'INVITE123',
|
||||
adopt_display_name: true,
|
||||
adopt_avatar: false
|
||||
})
|
||||
@@ -362,12 +373,48 @@ describe('OidcCallbackView', () => {
|
||||
expect(replace).toHaveBeenCalledWith('/welcome')
|
||||
})
|
||||
|
||||
it('switches to bind-login when create-account returns EMAIL_EXISTS', async () => {
|
||||
exchangePendingOAuthCompletion.mockResolvedValue({
|
||||
error: 'email_required',
|
||||
redirect: '/welcome'
|
||||
})
|
||||
apiClientPost.mockRejectedValue({
|
||||
response: {
|
||||
data: {
|
||||
reason: 'EMAIL_EXISTS',
|
||||
message: 'email already exists'
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const wrapper = mount(OidcCallbackView, {
|
||||
global: {
|
||||
stubs: {
|
||||
AuthLayout: { template: '<div><slot /></div>' },
|
||||
Icon: true,
|
||||
RouterLink: { template: '<a><slot /></a>' },
|
||||
transition: false
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
await flushPromises()
|
||||
await wrapper.get('[data-testid="oidc-create-account-email"]').setValue('existing@example.com')
|
||||
await wrapper.get('[data-testid="oidc-create-account-password"]').setValue('secret-123')
|
||||
await wrapper.get('[data-testid="oidc-create-account-submit"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect((wrapper.get('[data-testid="oidc-bind-login-email"]').element as HTMLInputElement).value).toBe(
|
||||
'existing@example.com'
|
||||
)
|
||||
})
|
||||
|
||||
it('sends a verify code for pending oauth account creation', async () => {
|
||||
exchangePendingOAuthCompletion.mockResolvedValue({
|
||||
error: 'email_required',
|
||||
redirect: '/welcome'
|
||||
})
|
||||
sendVerifyCode.mockResolvedValue({
|
||||
sendPendingOAuthVerifyCode.mockResolvedValue({
|
||||
message: 'sent',
|
||||
countdown: 60
|
||||
})
|
||||
@@ -389,7 +436,7 @@ describe('OidcCallbackView', () => {
|
||||
await wrapper.get('[data-testid="oidc-create-account-send-code"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(sendVerifyCode).toHaveBeenCalledWith({
|
||||
expect(sendPendingOAuthVerifyCode).toHaveBeenCalledWith({
|
||||
email: 'new@example.com'
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,6 +8,8 @@ const {
|
||||
login2FAMock,
|
||||
apiClientPostMock,
|
||||
sendVerifyCodeMock,
|
||||
sendPendingOAuthVerifyCodeMock,
|
||||
getPublicSettingsMock,
|
||||
prepareOAuthBindAccessTokenCookieMock,
|
||||
getAuthTokenMock,
|
||||
replaceMock,
|
||||
@@ -24,6 +26,8 @@ const {
|
||||
login2FAMock: vi.fn(),
|
||||
apiClientPostMock: vi.fn(),
|
||||
sendVerifyCodeMock: vi.fn(),
|
||||
sendPendingOAuthVerifyCodeMock: vi.fn(),
|
||||
getPublicSettingsMock: vi.fn(),
|
||||
prepareOAuthBindAccessTokenCookieMock: vi.fn(),
|
||||
getAuthTokenMock: vi.fn(),
|
||||
replaceMock: vi.fn(),
|
||||
@@ -130,6 +134,8 @@ vi.mock('@/api/auth', async () => {
|
||||
completeWeChatOAuthRegistration: (...args: any[]) => completeWeChatOAuthRegistrationMock(...args),
|
||||
login2FA: (...args: any[]) => login2FAMock(...args),
|
||||
sendVerifyCode: (...args: any[]) => sendVerifyCodeMock(...args),
|
||||
sendPendingOAuthVerifyCode: (...args: any[]) => sendPendingOAuthVerifyCodeMock(...args),
|
||||
getPublicSettings: (...args: any[]) => getPublicSettingsMock(...args),
|
||||
prepareOAuthBindAccessTokenCookie: (...args: any[]) => prepareOAuthBindAccessTokenCookieMock(...args),
|
||||
getAuthToken: (...args: any[]) => getAuthTokenMock(...args),
|
||||
}
|
||||
@@ -142,6 +148,8 @@ describe('WechatCallbackView', () => {
|
||||
login2FAMock.mockReset()
|
||||
apiClientPostMock.mockReset()
|
||||
sendVerifyCodeMock.mockReset()
|
||||
sendPendingOAuthVerifyCodeMock.mockReset()
|
||||
getPublicSettingsMock.mockReset()
|
||||
replaceMock.mockReset()
|
||||
setTokenMock.mockReset()
|
||||
showSuccessMock.mockReset()
|
||||
@@ -167,6 +175,11 @@ describe('WechatCallbackView', () => {
|
||||
configurable: true,
|
||||
value: 'Mozilla/5.0',
|
||||
})
|
||||
getPublicSettingsMock.mockResolvedValue({
|
||||
invitation_code_enabled: false,
|
||||
turnstile_enabled: false,
|
||||
turnstile_site_key: '',
|
||||
})
|
||||
})
|
||||
|
||||
it('overrides an incompatible query mode with the configured open capability during bind recovery', async () => {
|
||||
@@ -478,6 +491,11 @@ describe('WechatCallbackView', () => {
|
||||
})
|
||||
|
||||
it('collects email, password, and verify code for pending oauth account creation and submits adoption decisions', async () => {
|
||||
getPublicSettingsMock.mockResolvedValue({
|
||||
invitation_code_enabled: true,
|
||||
turnstile_enabled: false,
|
||||
turnstile_site_key: '',
|
||||
})
|
||||
exchangePendingOAuthCompletionMock.mockResolvedValue({
|
||||
error: 'email_required',
|
||||
redirect: '/welcome',
|
||||
@@ -514,6 +532,7 @@ describe('WechatCallbackView', () => {
|
||||
await wrapper.get('[data-testid="wechat-create-account-email"]').setValue(' new@example.com ')
|
||||
await wrapper.get('[data-testid="wechat-create-account-password"]').setValue('secret-123')
|
||||
await wrapper.get('[data-testid="wechat-create-account-verify-code"]').setValue('246810')
|
||||
await wrapper.get('[data-testid="wechat-create-account-invitation-code"]').setValue(' INVITE123 ')
|
||||
await wrapper.get('[data-testid="wechat-create-account-submit"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
@@ -521,6 +540,7 @@ describe('WechatCallbackView', () => {
|
||||
email: 'new@example.com',
|
||||
password: 'secret-123',
|
||||
verify_code: '246810',
|
||||
invitation_code: 'INVITE123',
|
||||
adopt_display_name: true,
|
||||
adopt_avatar: false,
|
||||
})
|
||||
@@ -528,12 +548,48 @@ describe('WechatCallbackView', () => {
|
||||
expect(replaceMock).toHaveBeenCalledWith('/welcome')
|
||||
})
|
||||
|
||||
it('switches to bind-login when create-account returns EMAIL_EXISTS', async () => {
|
||||
exchangePendingOAuthCompletionMock.mockResolvedValue({
|
||||
error: 'email_required',
|
||||
redirect: '/welcome',
|
||||
})
|
||||
apiClientPostMock.mockRejectedValue({
|
||||
response: {
|
||||
data: {
|
||||
reason: 'EMAIL_EXISTS',
|
||||
message: 'email already exists',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const wrapper = mount(WechatCallbackView, {
|
||||
global: {
|
||||
stubs: {
|
||||
AuthLayout: { template: '<div><slot /></div>' },
|
||||
Icon: true,
|
||||
RouterLink: { template: '<a><slot /></a>' },
|
||||
transition: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await flushPromises()
|
||||
await wrapper.get('[data-testid="wechat-create-account-email"]').setValue('existing@example.com')
|
||||
await wrapper.get('[data-testid="wechat-create-account-password"]').setValue('secret-123')
|
||||
await wrapper.get('[data-testid="wechat-create-account-submit"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect((wrapper.get('[data-testid="wechat-bind-login-email"]').element as HTMLInputElement).value).toBe(
|
||||
'existing@example.com'
|
||||
)
|
||||
})
|
||||
|
||||
it('sends a verify code for pending oauth account creation', async () => {
|
||||
exchangePendingOAuthCompletionMock.mockResolvedValue({
|
||||
error: 'email_required',
|
||||
redirect: '/welcome',
|
||||
})
|
||||
sendVerifyCodeMock.mockResolvedValue({
|
||||
sendPendingOAuthVerifyCodeMock.mockResolvedValue({
|
||||
message: 'sent',
|
||||
countdown: 60,
|
||||
})
|
||||
@@ -555,7 +611,7 @@ describe('WechatCallbackView', () => {
|
||||
await wrapper.get('[data-testid="wechat-create-account-send-code"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(sendVerifyCodeMock).toHaveBeenCalledWith({
|
||||
expect(sendPendingOAuthVerifyCodeMock).toHaveBeenCalledWith({
|
||||
email: 'new@example.com',
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user