refactor(system): extract reset-password popup into ResetPasswordDialog (#3047)

* refactor(system): extract reset-password popup into ResetPasswordDialog

* fix(system): preserve pending password resets across tab changes

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
main
MidoriKurage 2026-09-07 13:26:59 +08:00 committed by GitHub
parent 6f5a9c8c31
commit fee252e936
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 334 additions and 144 deletions

View File

@ -11,8 +11,7 @@
Visibility is owned by the parent via v-model:visible. Every user-visible
message is also emitted via `announced` so the parent's sr-only live
region can relay it. Shared popup chrome comes from systemAdminDialog.less
(imported by SystemSettings.vue).
region can relay it. Shared popup chrome comes from systemAdminDialog.less.
-->
<template>
<t-popup :visible="visible" trigger="click" placement="left-top" :destroy-on-close="!locked"

View File

@ -0,0 +1,155 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { runInNewContext } from 'node:vm'
import * as vue from 'vue'
import { compileScript, compileTemplate, parse } from 'vue/compiler-sfc'
import ts from 'typescript'
const read = (file) => readFileSync(new URL(file, import.meta.url), 'utf8')
const flush = () => new Promise(setImmediate)
function compileComponent(source, imports) {
const { descriptor } = parse(source)
const script = compileScript(descriptor, { id: 'reset-test' })
const template = compileTemplate({
source: descriptor.template.content,
filename: 'ResetPasswordDialog.vue',
id: 'reset-test',
compilerOptions: { bindingMetadata: script.bindings },
})
assert.deepEqual(template.errors, [])
const evaluate = (source) => {
const exports = {}
const { outputText } = ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
})
runInNewContext(outputText, {
exports,
require(name) {
if (name === 'vue') return vue
assert.ok(name in imports, `Unexpected import: ${name}`)
return imports[name]
},
})
return exports
}
return Object.assign(evaluate(script.content).default, { render: evaluate(template.code).render })
}
function mountResetRow() {
const requests = []
const notices = []
const Dialog = compileComponent(read('./ResetPasswordDialog.vue'), {
'tdesign-vue-next': { MessagePlugin: { success: (msg) => notices.push(msg), error: (msg) => notices.push(msg) } },
'vue-i18n': { useI18n: () => ({ t: (key) => key }) },
'@/api/auth': { getAuthConfig: async () => ({ complex_password_enabled: true }) },
'@/utils/passwordPolicy': { newPasswordRules: () => [] },
'@/api/system': {
resetUserPassword: (body) => new Promise((resolve, reject) => requests.push({ body, resolve, reject })),
},
})
// Compile the real parent row so reverting its lifetime/visibility binding
// also fails this test, instead of testing a hand-written approximation.
const { descriptor } = parse(read('./SystemSettings.vue'))
function findRow(node) {
if (node.props?.some((prop) => prop.name === 'class' && prop.value?.content.includes('setting-row--password-reset'))) {
return node.loc.source
}
return node.children?.map(findRow).find(Boolean)
}
const row = findRow(descriptor.template.ast)
assert.ok(row, 'password reset row must exist')
const Parent = compileComponent(`<template>${row.replace('<ResetPasswordDialog ', '<ResetPasswordDialog ref="dialogRef" ')}</template>
<script setup>
import { ref } from 'vue'
import ResetPasswordDialog from './ResetPasswordDialog.vue'
const activeSettingsSection = ref('access')
const passwordResetVisible = ref(false)
const saveAnnouncement = ref('')
const dialogRef = ref()
const t = (key) => key
</script>`, { './ResetPasswordDialog.vue': { default: Dialog, __esModule: true } })
const renderer = vue.createRenderer({
createElement: (tag) => ({ tag, children: [], style: {} }),
createText: (text) => ({ text }),
createComment: (text) => ({ text }),
insert(child, parent, anchor) {
if (child.parent) child.parent.children = child.parent.children.filter((item) => item !== child)
const index = anchor ? parent.children.indexOf(anchor) : -1
parent.children.splice(index < 0 ? parent.children.length : index, 0, child)
child.parent = parent
},
remove(child) {
if (child.parent) child.parent.children = child.parent.children.filter((item) => item !== child)
child.parent = null
},
parentNode: (node) => node?.parent,
nextSibling: (node) => node.parent?.children[node.parent.children.indexOf(node) + 1] ?? null,
setText(node, text) { node.text = text },
setElementText(node, text) { node.children = []; node.text = text },
patchProp(node, key, _, value) { if (key !== 'style') node[key] = value },
})
const passthrough = { setup: (_, { slots }) => () => vue.h('div', slots.default?.()) }
const app = renderer.createApp(Parent)
for (const name of ['t-button', 't-tag', 't-icon', 't-input', 't-form-item']) app.component(name, passthrough)
app.component('t-form', {
setup(_, { slots, expose }) {
expose({ validate: async () => true, clearValidate() {} })
return () => vue.h('form', slots.default?.())
},
})
app.component('t-popup', {
props: ['visible'],
setup: (props, { slots }) => () => vue.h('div', [slots.default?.(), props.visible ? slots.content?.() : null]),
})
app.mount({ children: [] })
const parent = app._instance.setupState
return { app, parent, requests, notices, dialog: () => parent.dialogRef.$.setupState }
}
for (const outcome of ['success', 'failure']) {
test(`pending reset survives tab changes and reports ${outcome}`, async (t) => {
const { app, parent, requests, dialog } = mountResetRow()
t.after(() => app.unmount())
parent.passwordResetVisible = true
await flush()
const initial = dialog()
Object.assign(initial.form, { email: ' user@example.com ', newPassword: 'FirstSecret1!', confirmPassword: 'FirstSecret1!' })
const pending = initial.submit()
await flush()
assert.equal(requests.length, 1)
assert.equal(requests[0].body.email, 'user@example.com')
initial.onVisibleChange(false)
assert.equal(parent.passwordResetVisible, true)
parent.activeSettingsSection = 'runtime'
await flush()
assert.equal(dialog(), initial, 'tab changes must preserve the pending request owner')
assert.equal(parent.dialogRef.$.subTree.component.props.visible, false, 'teleported popup must be hidden')
parent.activeSettingsSection = 'access'
await flush()
assert.equal(dialog(), initial)
assert.equal(parent.dialogRef.$.subTree.component.props.visible, true)
assert.equal(initial.complexPasswordEnabled, true)
assert.equal(initial.submitting, true)
assert.equal(initial.form.newPassword, 'FirstSecret1!')
await initial.submit()
assert.equal(requests.length, 1, 'returning to the tab must not allow a concurrent reset')
parent.activeSettingsSection = 'runtime'
await flush()
if (outcome === 'success') requests[0].resolve({})
else requests[0].reject(new Error('Reset failed'))
await pending
await flush()
assert.equal(initial.submitting, false)
assert.equal(parent.saveAnnouncement, outcome === 'success' ? 'system.globalSettings.passwordReset.success' : 'Reset failed')
assert.equal(parent.passwordResetVisible, outcome !== 'success')
parent.activeSettingsSection = 'access'
await flush()
assert.equal(parent.dialogRef.$.subTree.component.props.visible, outcome !== 'success')
assert.equal(initial.form.newPassword, outcome === 'success' ? '' : 'FirstSecret1!')
})
}

View File

@ -0,0 +1,164 @@
<!--
ResetPasswordDialog: SystemAdmin "reset user password" in-place popup
for the Access row.
The trigger button goes in the default slot. The parent owns visibility
via v-model:visible and relays the `announced` event into its sr-only
live region.
-->
<template>
<t-popup :visible="visible && active" trigger="click" placement="left-top" destroy-on-close
overlay-class-name="system-admin-action-popup-overlay" @visible-change="onVisibleChange">
<span class="system-admin-action-popup-anchor">
<slot />
</span>
<template #content>
<div class="system-admin-action-popup-inner" @click.stop>
<div class="system-admin-action-popup-title">
{{ t('system.globalSettings.passwordReset.dialogTitle') }}
</div>
<p class="system-admin-action-popup-hint">
{{ t('system.globalSettings.passwordReset.warning') }}
</p>
<t-form ref="formRef" :data="form" :rules="rules" label-align="top" class="system-admin-action-popup-form">
<t-form-item :label="t('system.globalSettings.passwordReset.emailLabel')" name="email">
<t-input v-model="form.email" type="text" clearable autocomplete="off" :disabled="submitting"
:placeholder="t('system.globalSettings.passwordReset.emailPlaceholder')" />
</t-form-item>
<t-form-item :label="t('system.globalSettings.passwordReset.newPasswordLabel')" name="newPassword">
<t-input v-model="form.newPassword" type="password" autocomplete="new-password" :disabled="submitting"
:placeholder="t('system.globalSettings.passwordReset.newPasswordPlaceholder')">
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</t-form-item>
<t-form-item :label="t('system.globalSettings.passwordReset.confirmPasswordLabel')" name="confirmPassword">
<t-input v-model="form.confirmPassword" type="password" autocomplete="new-password" :disabled="submitting"
:placeholder="t('system.globalSettings.passwordReset.confirmPasswordPlaceholder')" @enter="submit">
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</t-form-item>
</t-form>
<div class="system-admin-action-popup-footer">
<t-button variant="outline" :disabled="submitting" @click="emit('update:visible', false)">
{{ t('system.globalSettings.confirm.cancelBtn') }}
</t-button>
<t-button theme="danger" :loading="submitting" @click="submit">
{{ t('system.globalSettings.passwordReset.confirmBtn') }}
</t-button>
</div>
</div>
</template>
</t-popup>
</template>
<script setup lang="ts">
import { computed, nextTick, reactive, ref, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import type { FormInstanceFunctions, FormRule } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { resetUserPassword } from '@/api/system'
import { getAuthConfig } from '@/api/auth'
import { newPasswordRules } from '@/utils/passwordPolicy'
// Hide the teleported popup on other tabs without discarding a pending reset.
const props = defineProps<{ visible: boolean; active: boolean }>()
const emit = defineEmits<{
'update:visible': [boolean]
announced: [string]
}>()
const { t } = useI18n()
const submitting = ref(false)
const formRef = ref<FormInstanceFunctions>()
const form = reactive({
email: '',
newPassword: '',
confirmPassword: '',
})
const complexPasswordEnabled = ref(false)
const loadAuthConfig = async () => {
try {
const resp = await getAuthConfig()
complexPasswordEnabled.value = !!resp.complex_password_enabled
} catch (err: any) {
const msg = err?.message || t('system.globalSettings.messages.loadFailed')
MessagePlugin.error(msg)
complexPasswordEnabled.value = false
}
}
const rules = computed<Record<string, FormRule[]>>(() => ({
email: [
{ required: true, message: t('auth.emailRequired'), type: 'error' },
{ email: true, message: t('auth.emailInvalid'), type: 'error' }
],
newPassword: newPasswordRules(t, complexPasswordEnabled.value),
confirmPassword: [
{ required: true, message: t('auth.confirmPasswordRequired'), trigger: 'blur' },
{
validator: (value: string) => value === form.newPassword,
message: t('auth.passwordMismatch'),
trigger: 'blur',
},
],
}))
function resetFormFields() {
form.email = ''
form.newPassword = ''
form.confirmPassword = ''
formRef.value?.clearValidate?.()
}
// destroy-on-close remounts the form DOM on every open, so the fields
// start empty regardless; the explicit reset + clearValidate here just
// guarantees the reactive state and any stale inline errors are gone too
// (mirrors the pre-refactor behaviour in SystemSettings).
watch(() => props.visible, async (visible) => {
if (!visible) {
resetFormFields()
return
}
resetFormFields()
await loadAuthConfig()
await nextTick()
formRef.value?.clearValidate?.()
})
function onVisibleChange(visible: boolean) {
// Never let an outside click or Esc collapse the popup while a reset
// roundtrip is in flight, so the write can't be orphaned. Emitting
// nothing keeps the parent's v-model:visible true and the popup open.
if (!visible && submitting.value) return
emit('update:visible', visible)
}
async function submit() {
if (submitting.value) return
submitting.value = true
try {
const valid = await formRef.value?.validate?.()
if (valid !== true) return
await resetUserPassword({
email: form.email.trim(),
new_password: form.newPassword,
})
const success = t('system.globalSettings.passwordReset.success')
emit('announced', success)
MessagePlugin.success(success)
emit('update:visible', false)
} catch (err: any) {
const msg = err?.message || t('system.globalSettings.passwordReset.failed')
emit('announced', msg)
MessagePlugin.error(msg)
} finally {
submitting.value = false
}
}
</script>
<style lang="less">
@import './systemAdminDialog.less';
</style>

View File

@ -130,7 +130,8 @@
</div>
</div>
<div v-if="activeSettingsSection === 'access'" class="setting-row setting-row--password-reset">
<!-- Keep the reset request and its submit lock alive across tab changes. -->
<div v-show="activeSettingsSection === 'access'" class="setting-row setting-row--password-reset">
<div class="setting-info">
<div class="setting-label">
<span>{{ t('system.globalSettings.passwordReset.label') }}</span>
@ -141,59 +142,13 @@
<p class="desc">{{ t('system.globalSettings.passwordReset.description') }}</p>
</div>
<div class="setting-control">
<t-popup :visible="passwordResetVisible" trigger="click" placement="left-top" destroy-on-close
overlay-class-name="system-admin-action-popup-overlay" @visible-change="onPasswordResetVisibleChange">
<span class="system-admin-action-popup-anchor">
<t-button theme="danger" variant="text" class="password-reset-trigger">
<template #icon><t-icon name="lock-on" /></template>
{{ t('system.globalSettings.passwordReset.action') }}
</t-button>
</span>
<template #content>
<div class="system-admin-action-popup-inner" @click.stop>
<div class="system-admin-action-popup-title">
{{ t('system.globalSettings.passwordReset.dialogTitle') }}
</div>
<p class="system-admin-action-popup-hint">
{{ t('system.globalSettings.passwordReset.warning') }}
</p>
<t-form ref="passwordResetFormRef" :data="passwordResetForm" :rules="passwordResetRules"
label-align="top" class="system-admin-action-popup-form">
<t-form-item :label="t('system.globalSettings.passwordReset.emailLabel')" name="email">
<t-input v-model="passwordResetForm.email" type="text" clearable autocomplete="off"
:disabled="passwordResetSubmitting"
:placeholder="t('system.globalSettings.passwordReset.emailPlaceholder')" />
</t-form-item>
<t-form-item :label="t('system.globalSettings.passwordReset.newPasswordLabel')"
name="newPassword">
<t-input v-model="passwordResetForm.newPassword" type="password" autocomplete="new-password"
:disabled="passwordResetSubmitting"
:placeholder="t('system.globalSettings.passwordReset.newPasswordPlaceholder')">
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</t-form-item>
<t-form-item :label="t('system.globalSettings.passwordReset.confirmPasswordLabel')"
name="confirmPassword">
<t-input v-model="passwordResetForm.confirmPassword" type="password" autocomplete="new-password"
:disabled="passwordResetSubmitting"
:placeholder="t('system.globalSettings.passwordReset.confirmPasswordPlaceholder')"
@enter="submitPasswordReset">
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</t-form-item>
</t-form>
<div class="system-admin-action-popup-footer">
<t-button variant="outline" :disabled="passwordResetSubmitting"
@click="passwordResetVisible = false">
{{ t('system.globalSettings.confirm.cancelBtn') }}
</t-button>
<t-button theme="danger" :loading="passwordResetSubmitting" @click="submitPasswordReset">
{{ t('system.globalSettings.passwordReset.confirmBtn') }}
</t-button>
</div>
</div>
</template>
</t-popup>
<ResetPasswordDialog v-model:visible="passwordResetVisible" :active="activeSettingsSection === 'access'"
@announced="saveAnnouncement = $event">
<t-button theme="danger" variant="text" class="password-reset-trigger">
<template #icon><t-icon name="lock-on" /></template>
{{ t('system.globalSettings.passwordReset.action') }}
</t-button>
</ResetPasswordDialog>
</div>
</div>
@ -373,7 +328,6 @@
import { ref, reactive, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import type { FormInstanceFunctions, FormRule } from 'tdesign-vue-next'
import {
listSystemSettings,
updateSystemSetting,
@ -382,14 +336,13 @@ import {
listSystemAdmins,
promoteUserToSystemAdmin,
revokeSystemAdmin,
resetUserPassword,
type SystemSettingItem,
} from '@/api/system'
import { getAuthConfig } from '@/api/auth'
import CreateUserDialog from './CreateUserDialog.vue'
import ResetPasswordDialog from './ResetPasswordDialog.vue'
import { useAuthStore } from '@/stores/auth'
import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'
import { newPasswordRules, PASSWORD_SPECIAL_CHARS } from '@/utils/passwordPolicy'
import { PASSWORD_SPECIAL_CHARS } from '@/utils/passwordPolicy'
import { isSettingValueDirty, resolveCurrentSetting } from './systemSettingsEdit'
const authStore = useAuthStore()
@ -604,87 +557,10 @@ const adminEmails = ref<string[]>([])
const adminEmailToId = ref<Record<string, string>>({})
const adminBusy = ref(false)
// Access-row popups each live in their own dialog component
// (CreateUserDialog.vue / ResetPasswordDialog.vue, same Access row);
// only their visibility is owned here.
const passwordResetVisible = ref(false)
const passwordResetSubmitting = ref(false)
const passwordResetFormRef = ref<FormInstanceFunctions>()
const passwordResetForm = reactive({
email: '',
newPassword: '',
confirmPassword: '',
})
const passwordResetRules = computed(() => ({
email: [
{ required: true, message: t('auth.emailRequired'), type: 'error' },
{ email: true, message: t('auth.emailInvalid'), type: 'error' }
],
newPassword: newPasswordRules(t, complexPasswordEnabled.value),
confirmPassword: [
{ required: true, message: t('auth.confirmPasswordRequired'), trigger: 'blur' },
{
validator: (value: string) => value === passwordResetForm.newPassword,
message: t('auth.passwordMismatch'),
trigger: 'blur',
},
],
}))
const complexPasswordEnabled = ref(false)
const loadAuthConfig = async () => {
try {
const resp = await getAuthConfig()
complexPasswordEnabled.value = !!resp.complex_password_enabled
} catch (err: any) {
const msg = err?.message || t('system.globalSettings.messages.loadFailed')
MessagePlugin.error(msg)
complexPasswordEnabled.value = false
}
}
function resetPasswordResetForm() {
passwordResetForm.email = ''
passwordResetForm.newPassword = ''
passwordResetForm.confirmPassword = ''
passwordResetFormRef.value?.clearValidate?.()
}
async function onPasswordResetVisibleChange(visible: boolean) {
if (!visible && passwordResetSubmitting.value) return
passwordResetVisible.value = visible
if (visible) {
await loadAuthConfig()
resetPasswordResetForm()
await nextTick()
passwordResetFormRef.value?.clearValidate?.()
return
}
resetPasswordResetForm()
}
async function submitPasswordReset() {
if (passwordResetSubmitting.value) return
passwordResetSubmitting.value = true
try {
const valid = await passwordResetFormRef.value?.validate?.()
if (valid !== true) return
await resetUserPassword({
email: passwordResetForm.email.trim(),
new_password: passwordResetForm.newPassword,
})
saveAnnouncement.value = t('system.globalSettings.passwordReset.success')
MessagePlugin.success(t('system.globalSettings.passwordReset.success'))
passwordResetVisible.value = false
} catch (err: any) {
const msg = err?.message || t('system.globalSettings.passwordReset.failed')
saveAnnouncement.value = msg
MessagePlugin.error(msg)
} finally {
passwordResetSubmitting.value = false
}
}
// Create-user popup lives in CreateUserDialog.vue (same Access row);
// only its visibility is owned here.
const createUserVisible = ref(false)
// Guards ssrf.whitelist while an async confirm roundtrip is in flight.
@ -1638,7 +1514,3 @@ onUnmounted(() => {
}
}
</style>
<style lang="less">
@import './systemAdminDialog.less';
</style>