auth page enhancement
This commit is contained in:
@@ -101,6 +101,8 @@ const breadcrumbItems = computed(() => {
|
|||||||
'/refunds': '退款列表',
|
'/refunds': '退款列表',
|
||||||
'/refund-items': '退款子项',
|
'/refund-items': '退款子项',
|
||||||
'/mq-status': '队列监控',
|
'/mq-status': '队列监控',
|
||||||
|
'/profile': '个人信息',
|
||||||
|
'/profile/password': '修改密码',
|
||||||
}
|
}
|
||||||
|
|
||||||
const items: Array<{ title: string; path: string }> = [{ title: '首页', path: '/' }]
|
const items: Array<{ title: string; path: string }> = [{ title: '首页', path: '/' }]
|
||||||
@@ -133,11 +135,11 @@ const breadcrumbItems = computed(() => {
|
|||||||
</span>
|
</span>
|
||||||
<template #overlay>
|
<template #overlay>
|
||||||
<a-menu>
|
<a-menu>
|
||||||
<a-menu-item key="profile">
|
<a-menu-item key="profile" @click="router.push('/profile')">
|
||||||
<SettingOutlined class="mr-2" />
|
<SettingOutlined class="mr-2" />
|
||||||
个人信息
|
个人信息
|
||||||
</a-menu-item>
|
</a-menu-item>
|
||||||
<a-menu-item key="password">
|
<a-menu-item key="password" @click="router.push('/profile/password')">
|
||||||
<KeyOutlined class="mr-2" />
|
<KeyOutlined class="mr-2" />
|
||||||
修改密码
|
修改密码
|
||||||
</a-menu-item>
|
</a-menu-item>
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ function createTestRouter() {
|
|||||||
{ path: '/users', component: { template: '<div>Users</div>' } },
|
{ path: '/users', component: { template: '<div>Users</div>' } },
|
||||||
{ path: '/orders', component: { template: '<div>Orders</div>' } },
|
{ path: '/orders', component: { template: '<div>Orders</div>' } },
|
||||||
{ path: '/login', component: { template: '<div>Login</div>' } },
|
{ path: '/login', component: { template: '<div>Login</div>' } },
|
||||||
|
{ path: '/profile', component: { template: '<div>Profile</div>' } },
|
||||||
|
{ path: '/profile/password', component: { template: '<div>Password</div>' } },
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -136,4 +138,44 @@ describe('MainLayout', () => {
|
|||||||
expect(breadcrumb.exists()).toBe(true)
|
expect(breadcrumb.exists()).toBe(true)
|
||||||
expect(breadcrumb.text()).toContain('首页')
|
expect(breadcrumb.text()).toContain('首页')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('navigates to /profile when clicking profile menu item', async () => {
|
||||||
|
const wrapper = await mountLayout()
|
||||||
|
const vm = wrapper.getCurrentComponent()
|
||||||
|
const router = vm.appContext.config.globalProperties.$router
|
||||||
|
|
||||||
|
// Find and click the profile menu item
|
||||||
|
const menuItems = wrapper.findAll('.ant-dropdown-menu-item, .ant-menu-item')
|
||||||
|
const profileItem = menuItems.find((item) => item.text().includes('个人信息'))
|
||||||
|
if (profileItem) {
|
||||||
|
await profileItem.trigger('click')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify the route in the router after navigation
|
||||||
|
await router.push('/profile')
|
||||||
|
expect(router.currentRoute.value.path).toBe('/profile')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('navigates to /profile/password when clicking password menu item', async () => {
|
||||||
|
const wrapper = await mountLayout()
|
||||||
|
const vm = wrapper.getCurrentComponent()
|
||||||
|
const router = vm.appContext.config.globalProperties.$router
|
||||||
|
|
||||||
|
await router.push('/profile/password')
|
||||||
|
expect(router.currentRoute.value.path).toBe('/profile/password')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders profile breadcrumb on /profile path', async () => {
|
||||||
|
const wrapper = await mountLayout('/profile')
|
||||||
|
const breadcrumb = wrapper.find('.ant-breadcrumb')
|
||||||
|
|
||||||
|
expect(breadcrumb.text()).toContain('个人信息')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders password breadcrumb on /profile/password path', async () => {
|
||||||
|
const wrapper = await mountLayout('/profile/password')
|
||||||
|
const breadcrumb = wrapper.find('.ant-breadcrumb')
|
||||||
|
|
||||||
|
expect(breadcrumb.text()).toContain('修改密码')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||||
|
import { setActivePinia, createPinia } from 'pinia'
|
||||||
|
import { mount, flushPromises } from '@vue/test-utils'
|
||||||
|
import { nextTick } from 'vue'
|
||||||
|
import { message } from 'ant-design-vue'
|
||||||
|
import { ApiError } from '@/types/api'
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
|
||||||
|
Object.defineProperty(window, 'matchMedia', {
|
||||||
|
writable: true,
|
||||||
|
value: (query: string) => ({
|
||||||
|
matches: false,
|
||||||
|
media: query,
|
||||||
|
onchange: null,
|
||||||
|
addListener: () => {},
|
||||||
|
removeListener: () => {},
|
||||||
|
addEventListener: () => {},
|
||||||
|
removeEventListener: () => {},
|
||||||
|
dispatchEvent: () => false,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('@/utils/request', () => ({
|
||||||
|
api: {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('vue-router', () => ({
|
||||||
|
useRouter: () => ({ push: vi.fn() }),
|
||||||
|
useRoute: () => ({ path: '/profile' }),
|
||||||
|
}))
|
||||||
|
|
||||||
|
describe('Profile Page', () => {
|
||||||
|
let wrapper: ReturnType<typeof mount>
|
||||||
|
|
||||||
|
const mockUser = { id: 1, username: 'testuser', email: 'test@example.com', role: 'admin', status: 1 }
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
setActivePinia(createPinia())
|
||||||
|
localStorage.clear()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
wrapper?.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
async function mountPage() {
|
||||||
|
const { api } = await import('@/utils/request')
|
||||||
|
vi.mocked(api.get).mockResolvedValue(mockUser)
|
||||||
|
|
||||||
|
const store = useUserStore()
|
||||||
|
store.setToken('h.p.s', 'r.p.s', true)
|
||||||
|
store.setUser({ ...mockUser })
|
||||||
|
|
||||||
|
const { default: ProfilePage } = await import('../index.vue')
|
||||||
|
wrapper = mount(ProfilePage, { attachTo: document.body })
|
||||||
|
await flushPromises()
|
||||||
|
await nextTick()
|
||||||
|
return wrapper
|
||||||
|
}
|
||||||
|
|
||||||
|
it('renders user info in descriptions', async () => {
|
||||||
|
await mountPage()
|
||||||
|
const html = wrapper.html()
|
||||||
|
|
||||||
|
expect(html).toContain('testuser')
|
||||||
|
expect(html).toContain('admin')
|
||||||
|
expect(html).toContain('1')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('pre-fills email form field', async () => {
|
||||||
|
await mountPage()
|
||||||
|
const vm = wrapper.getCurrentComponent().setupState
|
||||||
|
|
||||||
|
expect(vm.formState.email).toBe('test@example.com')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('submits profile update successfully', async () => {
|
||||||
|
const { api } = await import('@/utils/request')
|
||||||
|
const updatedUser = { ...mockUser, email: 'new@example.com' }
|
||||||
|
vi.mocked(api.put).mockResolvedValueOnce(updatedUser)
|
||||||
|
const successSpy = vi.spyOn(message, 'success').mockImplementation(() => ({}) as never)
|
||||||
|
|
||||||
|
await mountPage()
|
||||||
|
const vm = wrapper.getCurrentComponent().setupState
|
||||||
|
vm.formState.email = 'new@example.com'
|
||||||
|
vm.formRef = { validate: vi.fn().mockResolvedValue(true) }
|
||||||
|
await vm.handleSubmit()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(api.put).toHaveBeenCalledWith('/api/v1/me/profile', { email: 'new@example.com' })
|
||||||
|
expect(successSpy).toHaveBeenCalledWith('个人信息更新成功')
|
||||||
|
successSpy.mockRestore()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows error message on ApiError', async () => {
|
||||||
|
const { api } = await import('@/utils/request')
|
||||||
|
vi.mocked(api.put).mockRejectedValueOnce(new ApiError('邮箱已被占用', 422))
|
||||||
|
const errorSpy = vi.spyOn(message, 'error').mockImplementation(() => ({}) as never)
|
||||||
|
|
||||||
|
await mountPage()
|
||||||
|
const vm = wrapper.getCurrentComponent().setupState
|
||||||
|
vm.formRef = { validate: vi.fn().mockResolvedValue(true) }
|
||||||
|
await vm.handleSubmit()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith('邮箱已被占用')
|
||||||
|
errorSpy.mockRestore()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows network error on generic failure', async () => {
|
||||||
|
const { api } = await import('@/utils/request')
|
||||||
|
vi.mocked(api.put).mockRejectedValueOnce(new Error('Network failure'))
|
||||||
|
const errorSpy = vi.spyOn(message, 'error').mockImplementation(() => ({}) as never)
|
||||||
|
|
||||||
|
await mountPage()
|
||||||
|
const vm = wrapper.getCurrentComponent().setupState
|
||||||
|
vm.formRef = { validate: vi.fn().mockResolvedValue(true) }
|
||||||
|
await vm.handleSubmit()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith('更新失败,请检查网络连接')
|
||||||
|
errorSpy.mockRestore()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||||
|
import { setActivePinia, createPinia } from 'pinia'
|
||||||
|
import { mount, flushPromises } from '@vue/test-utils'
|
||||||
|
import { nextTick } from 'vue'
|
||||||
|
import { message } from 'ant-design-vue'
|
||||||
|
import { ApiError } from '@/types/api'
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
|
||||||
|
Object.defineProperty(window, 'matchMedia', {
|
||||||
|
writable: true,
|
||||||
|
value: (query: string) => ({
|
||||||
|
matches: false,
|
||||||
|
media: query,
|
||||||
|
onchange: null,
|
||||||
|
addListener: () => {},
|
||||||
|
removeListener: () => {},
|
||||||
|
addEventListener: () => {},
|
||||||
|
removeEventListener: () => {},
|
||||||
|
dispatchEvent: () => false,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('@/utils/request', () => ({
|
||||||
|
api: {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
const mockPush = vi.fn()
|
||||||
|
|
||||||
|
vi.mock('vue-router', () => ({
|
||||||
|
useRouter: () => ({ push: mockPush }),
|
||||||
|
useRoute: () => ({ path: '/profile/password' }),
|
||||||
|
}))
|
||||||
|
|
||||||
|
describe('Password Change Page', () => {
|
||||||
|
let wrapper: ReturnType<typeof mount>
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
setActivePinia(createPinia())
|
||||||
|
localStorage.clear()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
mockPush.mockReset()
|
||||||
|
vi.useFakeTimers()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
wrapper?.unmount()
|
||||||
|
vi.useRealTimers()
|
||||||
|
})
|
||||||
|
|
||||||
|
async function mountPage() {
|
||||||
|
const store = useUserStore()
|
||||||
|
store.setToken('h.p.s', 'r.p.s', true)
|
||||||
|
store.setUser({ id: 1, username: 'u', email: 'u@e.com', role: 'user', status: 1 })
|
||||||
|
|
||||||
|
const { default: PasswordPage } = await import('../password.vue')
|
||||||
|
wrapper = mount(PasswordPage, { attachTo: document.body })
|
||||||
|
await flushPromises()
|
||||||
|
await nextTick()
|
||||||
|
return wrapper
|
||||||
|
}
|
||||||
|
|
||||||
|
it('renders three password fields', async () => {
|
||||||
|
await mountPage()
|
||||||
|
const html = wrapper.html()
|
||||||
|
|
||||||
|
expect(html).toContain('当前密码')
|
||||||
|
expect(html).toContain('新密码')
|
||||||
|
expect(html).toContain('确认新密码')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('submits password change and redirects to login', async () => {
|
||||||
|
const { api } = await import('@/utils/request')
|
||||||
|
vi.mocked(api.put).mockResolvedValueOnce(undefined)
|
||||||
|
const successSpy = vi.spyOn(message, 'success').mockImplementation(() => ({}) as never)
|
||||||
|
|
||||||
|
await mountPage()
|
||||||
|
const vm = wrapper.getCurrentComponent().setupState
|
||||||
|
vm.formState.old_password = 'oldpass'
|
||||||
|
vm.formState.new_password = 'newpass123'
|
||||||
|
vm.formState.new_password_confirmation = 'newpass123'
|
||||||
|
vm.formRef = { validate: vi.fn().mockResolvedValue(true) }
|
||||||
|
await vm.handleSubmit()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(api.put).toHaveBeenCalledWith('/api/v1/me/password', {
|
||||||
|
old_password: 'oldpass',
|
||||||
|
new_password: 'newpass123',
|
||||||
|
new_password_confirmation: 'newpass123',
|
||||||
|
})
|
||||||
|
expect(successSpy).toHaveBeenCalledWith('密码修改成功,请重新登录')
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(1500)
|
||||||
|
expect(mockPush).toHaveBeenCalledWith('/login')
|
||||||
|
successSpy.mockRestore()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows error message on ApiError (wrong old password)', async () => {
|
||||||
|
const { api } = await import('@/utils/request')
|
||||||
|
vi.mocked(api.put).mockRejectedValueOnce(new ApiError('旧密码错误', 422))
|
||||||
|
const errorSpy = vi.spyOn(message, 'error').mockImplementation(() => ({}) as never)
|
||||||
|
|
||||||
|
await mountPage()
|
||||||
|
const vm = wrapper.getCurrentComponent().setupState
|
||||||
|
vm.formState.old_password = 'wrong'
|
||||||
|
vm.formState.new_password = 'newpass123'
|
||||||
|
vm.formState.new_password_confirmation = 'newpass123'
|
||||||
|
vm.formRef = { validate: vi.fn().mockResolvedValue(true) }
|
||||||
|
await vm.handleSubmit()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith('旧密码错误')
|
||||||
|
expect(mockPush).not.toHaveBeenCalled()
|
||||||
|
errorSpy.mockRestore()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows network error on generic failure', async () => {
|
||||||
|
const { api } = await import('@/utils/request')
|
||||||
|
vi.mocked(api.put).mockRejectedValueOnce(new Error('Network'))
|
||||||
|
const errorSpy = vi.spyOn(message, 'error').mockImplementation(() => ({}) as never)
|
||||||
|
|
||||||
|
await mountPage()
|
||||||
|
const vm = wrapper.getCurrentComponent().setupState
|
||||||
|
vm.formRef = { validate: vi.fn().mockResolvedValue(true) }
|
||||||
|
await vm.handleSubmit()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith('密码修改失败,请检查网络连接')
|
||||||
|
errorSpy.mockRestore()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not redirect on error', async () => {
|
||||||
|
const { api } = await import('@/utils/request')
|
||||||
|
vi.mocked(api.put).mockRejectedValueOnce(new ApiError('旧密码错误', 422))
|
||||||
|
vi.spyOn(message, 'error').mockImplementation(() => ({}) as never)
|
||||||
|
|
||||||
|
await mountPage()
|
||||||
|
const vm = wrapper.getCurrentComponent().setupState
|
||||||
|
vm.formRef = { validate: vi.fn().mockResolvedValue(true) }
|
||||||
|
await vm.handleSubmit()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(2000)
|
||||||
|
expect(mockPush).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
import { ApiError } from '@/types/api'
|
||||||
|
|
||||||
|
const userStore = useUserStore()
|
||||||
|
|
||||||
|
const formRef = ref()
|
||||||
|
const loading = ref(false)
|
||||||
|
|
||||||
|
const formState = reactive({
|
||||||
|
email: '',
|
||||||
|
})
|
||||||
|
|
||||||
|
const rules = {
|
||||||
|
email: [
|
||||||
|
{ type: 'string' as const, required: true, message: '请输入邮箱', trigger: 'blur' as const },
|
||||||
|
{ type: 'email' as const, message: '请输入有效的邮箱地址', trigger: 'blur' as const },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
if (userStore.user) {
|
||||||
|
formState.email = userStore.user.email || ''
|
||||||
|
}
|
||||||
|
userStore.fetchCurrentUser().then(() => {
|
||||||
|
if (userStore.user) {
|
||||||
|
formState.email = userStore.user.email || ''
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
try {
|
||||||
|
await formRef.value.validate()
|
||||||
|
loading.value = true
|
||||||
|
await userStore.updateProfile({ email: formState.email })
|
||||||
|
message.success('个人信息更新成功')
|
||||||
|
} catch (error: unknown) {
|
||||||
|
if (error && typeof error === 'object' && 'errorFields' in error) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (error instanceof ApiError) {
|
||||||
|
message.error(error.message)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
console.error('更新错误:', error)
|
||||||
|
message.error('更新失败,请检查网络连接')
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<a-card title="个人信息">
|
||||||
|
<a-descriptions :column="1" bordered class="mb-6">
|
||||||
|
<a-descriptions-item label="用户 ID">
|
||||||
|
{{ userStore.user?.id }}
|
||||||
|
</a-descriptions-item>
|
||||||
|
<a-descriptions-item label="用户名">
|
||||||
|
{{ userStore.user?.username }}
|
||||||
|
</a-descriptions-item>
|
||||||
|
<a-descriptions-item label="角色">
|
||||||
|
{{ userStore.user?.role }}
|
||||||
|
</a-descriptions-item>
|
||||||
|
</a-descriptions>
|
||||||
|
|
||||||
|
<a-form
|
||||||
|
ref="formRef"
|
||||||
|
:model="formState"
|
||||||
|
:rules="rules"
|
||||||
|
layout="vertical"
|
||||||
|
@finish="handleSubmit"
|
||||||
|
>
|
||||||
|
<a-form-item label="邮箱" name="email">
|
||||||
|
<a-input
|
||||||
|
v-model:value="formState.email"
|
||||||
|
placeholder="请输入邮箱地址"
|
||||||
|
/>
|
||||||
|
</a-form-item>
|
||||||
|
|
||||||
|
<a-form-item>
|
||||||
|
<a-button
|
||||||
|
type="primary"
|
||||||
|
html-type="submit"
|
||||||
|
:loading="loading"
|
||||||
|
>
|
||||||
|
保存修改
|
||||||
|
</a-button>
|
||||||
|
</a-form-item>
|
||||||
|
</a-form>
|
||||||
|
</a-card>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
import { ApiError } from '@/types/api'
|
||||||
|
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
const formRef = ref()
|
||||||
|
const loading = ref(false)
|
||||||
|
|
||||||
|
const formState = reactive({
|
||||||
|
old_password: '',
|
||||||
|
new_password: '',
|
||||||
|
new_password_confirmation: '',
|
||||||
|
})
|
||||||
|
|
||||||
|
const rules = {
|
||||||
|
old_password: [
|
||||||
|
{
|
||||||
|
type: 'string' as const,
|
||||||
|
required: true,
|
||||||
|
message: '请输入当前密码',
|
||||||
|
trigger: 'blur' as const,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
new_password: [
|
||||||
|
{
|
||||||
|
type: 'string' as const,
|
||||||
|
required: true,
|
||||||
|
message: '请输入新密码',
|
||||||
|
trigger: 'blur' as const,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'string' as const,
|
||||||
|
min: 6,
|
||||||
|
message: '密码长度至少为 6 个字符',
|
||||||
|
trigger: 'blur' as const,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
new_password_confirmation: [
|
||||||
|
{
|
||||||
|
type: 'string' as const,
|
||||||
|
required: true,
|
||||||
|
message: '请确认新密码',
|
||||||
|
trigger: 'blur' as const,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
validator: (_rule: unknown, value: string) => {
|
||||||
|
if (value !== formState.new_password) {
|
||||||
|
return Promise.reject('两次输入的密码不一致')
|
||||||
|
}
|
||||||
|
return Promise.resolve()
|
||||||
|
},
|
||||||
|
trigger: 'blur' as const,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
try {
|
||||||
|
await formRef.value.validate()
|
||||||
|
loading.value = true
|
||||||
|
await userStore.changePassword({
|
||||||
|
old_password: formState.old_password,
|
||||||
|
new_password: formState.new_password,
|
||||||
|
new_password_confirmation: formState.new_password_confirmation,
|
||||||
|
})
|
||||||
|
message.success('密码修改成功,请重新登录')
|
||||||
|
setTimeout(() => {
|
||||||
|
router.push('/login')
|
||||||
|
}, 1500)
|
||||||
|
} catch (error: unknown) {
|
||||||
|
if (error && typeof error === 'object' && 'errorFields' in error) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (error instanceof ApiError) {
|
||||||
|
message.error(error.message)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
console.error('密码修改错误:', error)
|
||||||
|
message.error('密码修改失败,请检查网络连接')
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<a-card title="修改密码">
|
||||||
|
<div class="max-w-md">
|
||||||
|
<a-form
|
||||||
|
ref="formRef"
|
||||||
|
:model="formState"
|
||||||
|
:rules="rules"
|
||||||
|
layout="vertical"
|
||||||
|
@finish="handleSubmit"
|
||||||
|
>
|
||||||
|
<a-form-item label="当前密码" name="old_password">
|
||||||
|
<a-input-password
|
||||||
|
v-model:value="formState.old_password"
|
||||||
|
placeholder="请输入当前密码"
|
||||||
|
/>
|
||||||
|
</a-form-item>
|
||||||
|
|
||||||
|
<a-form-item label="新密码" name="new_password">
|
||||||
|
<a-input-password
|
||||||
|
v-model:value="formState.new_password"
|
||||||
|
placeholder="请输入新密码(至少6位)"
|
||||||
|
/>
|
||||||
|
</a-form-item>
|
||||||
|
|
||||||
|
<a-form-item label="确认新密码" name="new_password_confirmation">
|
||||||
|
<a-input-password
|
||||||
|
v-model:value="formState.new_password_confirmation"
|
||||||
|
placeholder="请再次输入新密码"
|
||||||
|
/>
|
||||||
|
</a-form-item>
|
||||||
|
|
||||||
|
<a-form-item>
|
||||||
|
<a-button
|
||||||
|
type="primary"
|
||||||
|
html-type="submit"
|
||||||
|
:loading="loading"
|
||||||
|
>
|
||||||
|
修改密码
|
||||||
|
</a-button>
|
||||||
|
</a-form-item>
|
||||||
|
</a-form>
|
||||||
|
</div>
|
||||||
|
</a-card>
|
||||||
|
</template>
|
||||||
@@ -7,6 +7,7 @@ vi.mock('@/utils/request', () => ({
|
|||||||
api: {
|
api: {
|
||||||
get: vi.fn(),
|
get: vi.fn(),
|
||||||
post: vi.fn(),
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
},
|
},
|
||||||
}))
|
}))
|
||||||
|
|
||||||
@@ -178,6 +179,79 @@ describe('useUserStore', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('updateProfile', () => {
|
||||||
|
it('calls API and updates local state', async () => {
|
||||||
|
const { api } = await import('@/utils/request')
|
||||||
|
const updatedUser = { id: 1, username: 'u', email: 'new@e.com', role: 'user', status: 1 }
|
||||||
|
vi.mocked(api.put).mockResolvedValueOnce(updatedUser)
|
||||||
|
|
||||||
|
const store = useUserStore()
|
||||||
|
store.setToken('h.p.s', 'r.p.s', true)
|
||||||
|
const result = await store.updateProfile({ email: 'new@e.com' })
|
||||||
|
|
||||||
|
expect(api.put).toHaveBeenCalledWith('/api/v1/me/profile', { email: 'new@e.com' })
|
||||||
|
expect(result).toEqual(updatedUser)
|
||||||
|
expect(store.user).toEqual(updatedUser)
|
||||||
|
expect(JSON.parse(localStorage.getItem('user')!)).toEqual(updatedUser)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not update state on API error', async () => {
|
||||||
|
const { api } = await import('@/utils/request')
|
||||||
|
vi.mocked(api.put).mockRejectedValueOnce(new Error('fail'))
|
||||||
|
|
||||||
|
const store = useUserStore()
|
||||||
|
const originalUser = { id: 1, username: 'u', email: 'old@e.com', role: 'user', status: 1 }
|
||||||
|
store.setUser(originalUser)
|
||||||
|
|
||||||
|
await expect(store.updateProfile({ email: 'new@e.com' })).rejects.toThrow('fail')
|
||||||
|
expect(store.user).toEqual(originalUser)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('changePassword', () => {
|
||||||
|
it('calls API and triggers logout on success', async () => {
|
||||||
|
const { api } = await import('@/utils/request')
|
||||||
|
vi.mocked(api.put).mockResolvedValueOnce(undefined)
|
||||||
|
|
||||||
|
const store = useUserStore()
|
||||||
|
store.setToken('h.p.s', 'r.p.s', true)
|
||||||
|
store.setUser({ id: 1, username: 'u', email: 'u@e.com', role: 'user', status: 1 })
|
||||||
|
|
||||||
|
await store.changePassword({
|
||||||
|
old_password: 'old123',
|
||||||
|
new_password: 'new123',
|
||||||
|
new_password_confirmation: 'new123',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(api.put).toHaveBeenCalledWith('/api/v1/me/password', {
|
||||||
|
old_password: 'old123',
|
||||||
|
new_password: 'new123',
|
||||||
|
new_password_confirmation: 'new123',
|
||||||
|
})
|
||||||
|
expect(store.token).toBeNull()
|
||||||
|
expect(store.user).toBeNull()
|
||||||
|
expect(localStorage.getItem('access_token')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not logout on API error', async () => {
|
||||||
|
const { api } = await import('@/utils/request')
|
||||||
|
vi.mocked(api.put).mockRejectedValueOnce(new Error('旧密码错误'))
|
||||||
|
|
||||||
|
const store = useUserStore()
|
||||||
|
store.setToken('h.p.s', 'r.p.s', true)
|
||||||
|
store.setUser({ id: 1, username: 'u', email: 'u@e.com', role: 'user', status: 1 })
|
||||||
|
|
||||||
|
await expect(store.changePassword({
|
||||||
|
old_password: 'wrong',
|
||||||
|
new_password: 'new123',
|
||||||
|
new_password_confirmation: 'new123',
|
||||||
|
})).rejects.toThrow('旧密码错误')
|
||||||
|
|
||||||
|
expect(store.token).toBe('h.p.s')
|
||||||
|
expect(store.user).not.toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('computed properties', () => {
|
describe('computed properties', () => {
|
||||||
it('isAdmin returns true for admin role', () => {
|
it('isAdmin returns true for admin role', () => {
|
||||||
const store = useUserStore()
|
const store = useUserStore()
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ export interface UserInfo {
|
|||||||
email: string
|
email: string
|
||||||
role: string
|
role: string
|
||||||
status: number
|
status: number
|
||||||
|
ext?: Record<string, unknown> | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useUserStore = defineStore('user', () => {
|
export const useUserStore = defineStore('user', () => {
|
||||||
@@ -71,6 +72,21 @@ export const useUserStore = defineStore('user', () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function updateProfile(data: { email?: string; ext?: Record<string, unknown> }) {
|
||||||
|
const result = await api.put<UserInfo>('/api/v1/me/profile', data)
|
||||||
|
setUser(result)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
async function changePassword(data: {
|
||||||
|
old_password: string
|
||||||
|
new_password: string
|
||||||
|
new_password_confirmation: string
|
||||||
|
}) {
|
||||||
|
await api.put('/api/v1/me/password', data)
|
||||||
|
logout()
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
token,
|
token,
|
||||||
refreshToken,
|
refreshToken,
|
||||||
@@ -82,5 +98,7 @@ export const useUserStore = defineStore('user', () => {
|
|||||||
setUser,
|
setUser,
|
||||||
fetchCurrentUser,
|
fetchCurrentUser,
|
||||||
logout,
|
logout,
|
||||||
|
updateProfile,
|
||||||
|
changePassword,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user