Close profile identity and avatar loop
This commit is contained in:
@@ -61,6 +61,71 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="mt-4 rounded-2xl border border-gray-100 bg-white/90 p-4 dark:border-dark-700 dark:bg-dark-900/30"
|
||||
>
|
||||
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<h3 class="text-sm font-semibold text-gray-900 dark:text-white">
|
||||
{{ t('profile.avatar.title') }}
|
||||
</h3>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
{{ t('profile.avatar.description') }}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
data-testid="profile-avatar-delete"
|
||||
type="button"
|
||||
class="btn btn-secondary btn-sm"
|
||||
:disabled="avatarSaving"
|
||||
@click="handleAvatarDelete"
|
||||
>
|
||||
{{ t('common.delete') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 space-y-3">
|
||||
<label
|
||||
for="profile-avatar-input"
|
||||
class="text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400"
|
||||
>
|
||||
{{ t('profile.avatar.inputLabel') }}
|
||||
</label>
|
||||
<textarea
|
||||
id="profile-avatar-input"
|
||||
data-testid="profile-avatar-input"
|
||||
v-model="avatarDraft"
|
||||
rows="3"
|
||||
class="input min-h-[88px]"
|
||||
:placeholder="t('profile.avatar.inputPlaceholder')"
|
||||
/>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<label class="btn btn-secondary btn-sm cursor-pointer">
|
||||
<input
|
||||
data-testid="profile-avatar-file-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
class="hidden"
|
||||
@change="handleAvatarFileChange"
|
||||
>
|
||||
{{ t('profile.avatar.uploadAction') }}
|
||||
</label>
|
||||
<button
|
||||
data-testid="profile-avatar-save"
|
||||
type="button"
|
||||
class="btn btn-primary btn-sm"
|
||||
:disabled="avatarSaving"
|
||||
@click="handleAvatarSave"
|
||||
>
|
||||
{{ t('common.save') }}
|
||||
</button>
|
||||
<span class="text-xs text-gray-400 dark:text-gray-500">
|
||||
{{ t('profile.avatar.uploadHint') }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ProfileIdentityBindingsSection
|
||||
class="mt-4"
|
||||
:user="user"
|
||||
@@ -74,11 +139,15 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { userAPI } from '@/api'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import ProfileIdentityBindingsSection from '@/components/user/profile/ProfileIdentityBindingsSection.vue'
|
||||
import { useAppStore } from '@/stores/app'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import type { User, UserAuthProvider, UserProfileSourceContext } from '@/types'
|
||||
import { extractApiErrorMessage } from '@/utils/apiError'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
@@ -97,6 +166,12 @@ const props = withDefaults(
|
||||
)
|
||||
|
||||
const { t } = useI18n()
|
||||
const authStore = useAuthStore()
|
||||
const appStore = useAppStore()
|
||||
|
||||
const maxAvatarBytes = 100 * 1024
|
||||
const avatarDraft = ref(props.user?.avatar_url?.trim() || '')
|
||||
const avatarSaving = ref(false)
|
||||
|
||||
const providerLabels = computed<Record<UserAuthProvider, string>>(() => ({
|
||||
email: t('profile.authBindings.providers.email'),
|
||||
@@ -109,6 +184,13 @@ const avatarUrl = computed(() => props.user?.avatar_url?.trim() || '')
|
||||
const displayName = computed(() => props.user?.username?.trim() || props.user?.email?.trim() || 'User')
|
||||
const avatarInitial = computed(() => displayName.value.charAt(0).toUpperCase() || 'U')
|
||||
|
||||
watch(
|
||||
() => props.user?.avatar_url,
|
||||
(value) => {
|
||||
avatarDraft.value = value?.trim() || ''
|
||||
}
|
||||
)
|
||||
|
||||
function normalizeProvider(value: string): UserAuthProvider | null {
|
||||
const normalized = value.trim().toLowerCase()
|
||||
if (normalized === 'email' || normalized === 'linuxdo' || normalized === 'wechat') {
|
||||
@@ -205,4 +287,122 @@ const sourceHints = computed(() => {
|
||||
|
||||
return hints
|
||||
})
|
||||
|
||||
function estimateDataURLByteSize(value: string): number {
|
||||
const [, encoded = ''] = value.split(',', 2)
|
||||
const sanitized = encoded.replace(/\s+/g, '')
|
||||
const padding = sanitized.endsWith('==') ? 2 : sanitized.endsWith('=') ? 1 : 0
|
||||
return Math.max(0, Math.floor((sanitized.length * 3) / 4) - padding)
|
||||
}
|
||||
|
||||
function validateAvatarInput(value: string): string | null {
|
||||
const normalized = value.trim()
|
||||
if (!normalized) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (normalized.startsWith('data:')) {
|
||||
if (!/^data:image\/[a-zA-Z0-9.+-]+;base64,/i.test(normalized)) {
|
||||
appStore.showError(t('profile.avatar.invalidValue'))
|
||||
return null
|
||||
}
|
||||
if (estimateDataURLByteSize(normalized) > maxAvatarBytes) {
|
||||
appStore.showError(t('profile.avatar.fileTooLarge'))
|
||||
return null
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(normalized)
|
||||
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
|
||||
return normalized
|
||||
}
|
||||
} catch {
|
||||
// Invalid URL is handled below.
|
||||
}
|
||||
|
||||
appStore.showError(t('profile.avatar.invalidValue'))
|
||||
return null
|
||||
}
|
||||
|
||||
function readFileAsDataURL(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : '')
|
||||
reader.onerror = () => reject(reader.error ?? new Error('avatar_read_failed'))
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}
|
||||
|
||||
async function handleAvatarFileChange(event: Event) {
|
||||
const input = event.target as HTMLInputElement | null
|
||||
const file = input?.files?.[0]
|
||||
if (input) {
|
||||
input.value = ''
|
||||
}
|
||||
if (!file) {
|
||||
return
|
||||
}
|
||||
if (!file.type.startsWith('image/')) {
|
||||
appStore.showError(t('profile.avatar.invalidType'))
|
||||
return
|
||||
}
|
||||
if (file.size > maxAvatarBytes) {
|
||||
appStore.showError(t('profile.avatar.fileTooLarge'))
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const dataURL = await readFileAsDataURL(file)
|
||||
const normalized = validateAvatarInput(dataURL)
|
||||
if (!normalized) {
|
||||
return
|
||||
}
|
||||
avatarDraft.value = normalized
|
||||
} catch (error: unknown) {
|
||||
appStore.showError(extractApiErrorMessage(error, t('common.error')))
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAvatarSave() {
|
||||
const normalized = validateAvatarInput(avatarDraft.value)
|
||||
if (!normalized) {
|
||||
return
|
||||
}
|
||||
|
||||
avatarSaving.value = true
|
||||
try {
|
||||
const updated = await userAPI.updateProfile({ avatar_url: normalized })
|
||||
authStore.user = updated
|
||||
avatarDraft.value = updated.avatar_url?.trim() || ''
|
||||
appStore.showSuccess(t('profile.avatar.saveSuccess'))
|
||||
} catch (error: unknown) {
|
||||
appStore.showError(extractApiErrorMessage(error, t('common.error')))
|
||||
} finally {
|
||||
avatarSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAvatarDelete() {
|
||||
if (avatarSaving.value) {
|
||||
return
|
||||
}
|
||||
if (!avatarDraft.value.trim() && !props.user?.avatar_url?.trim()) {
|
||||
appStore.showError(t('profile.avatar.emptyDeleteHint'))
|
||||
return
|
||||
}
|
||||
|
||||
avatarSaving.value = true
|
||||
try {
|
||||
const updated = await userAPI.updateProfile({ avatar_url: '' })
|
||||
authStore.user = updated
|
||||
avatarDraft.value = ''
|
||||
appStore.showSuccess(t('profile.avatar.deleteSuccess'))
|
||||
} catch (error: unknown) {
|
||||
appStore.showError(extractApiErrorMessage(error, t('common.error')))
|
||||
} finally {
|
||||
avatarSaving.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import ProfileInfoCard from '@/components/user/profile/ProfileInfoCard.vue'
|
||||
import type { User } from '@/types'
|
||||
|
||||
const {
|
||||
updateProfileMock,
|
||||
showSuccessMock,
|
||||
showErrorMock,
|
||||
authStoreState
|
||||
} = vi.hoisted(() => ({
|
||||
updateProfileMock: vi.fn(),
|
||||
showSuccessMock: vi.fn(),
|
||||
showErrorMock: vi.fn(),
|
||||
authStoreState: {
|
||||
user: null as User | null
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/api', () => ({
|
||||
userAPI: {
|
||||
updateProfile: updateProfileMock
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/auth', () => ({
|
||||
useAuthStore: () => authStoreState
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/app', () => ({
|
||||
useAppStore: () => ({
|
||||
showSuccess: showSuccessMock,
|
||||
showError: showErrorMock
|
||||
})
|
||||
}))
|
||||
|
||||
vi.mock('@/utils/apiError', () => ({
|
||||
extractApiErrorMessage: (error: unknown) => (error as Error).message || 'request failed'
|
||||
}))
|
||||
|
||||
vi.mock('vue-i18n', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('vue-i18n')>()
|
||||
return {
|
||||
...actual,
|
||||
useI18n: () => ({
|
||||
t: (key: string, params?: Record<string, string>) => {
|
||||
if (key === 'profile.administrator') return 'Administrator'
|
||||
if (key === 'profile.user') return 'User'
|
||||
if (key === 'profile.avatar.title') return 'Profile avatar'
|
||||
if (key === 'profile.avatar.description') return 'Set avatar by image URL or upload'
|
||||
if (key === 'profile.avatar.inputLabel') return 'Avatar URL or data URL'
|
||||
if (key === 'profile.avatar.inputPlaceholder') return 'https://cdn.example.com/avatar.png'
|
||||
if (key === 'profile.avatar.uploadAction') return 'Upload image'
|
||||
if (key === 'profile.avatar.uploadHint') return 'Images must be 100KB or smaller'
|
||||
if (key === 'profile.avatar.saveSuccess') return 'Avatar updated'
|
||||
if (key === 'profile.avatar.deleteSuccess') return 'Avatar removed'
|
||||
if (key === 'profile.avatar.invalidType') return 'Please choose an image file'
|
||||
if (key === 'profile.avatar.fileTooLarge') return 'Avatar image must be 100KB or smaller'
|
||||
if (key === 'profile.avatar.invalidValue') return 'Enter a valid avatar URL or image data URL'
|
||||
if (key === 'profile.avatar.emptyDeleteHint') return 'Avatar already removed'
|
||||
if (key === 'profile.authBindings.providers.email') return 'Email'
|
||||
if (key === 'profile.authBindings.providers.linuxdo') return 'LinuxDo'
|
||||
if (key === 'profile.authBindings.providers.wechat') return 'WeChat'
|
||||
if (key === 'profile.authBindings.providers.oidc') return params?.providerName || 'OIDC'
|
||||
if (key === 'common.save') return 'Save'
|
||||
if (key === 'common.delete') return 'Delete'
|
||||
return key
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
function createUser(overrides: Partial<User> = {}): User {
|
||||
return {
|
||||
id: 5,
|
||||
username: 'alice',
|
||||
email: 'alice@example.com',
|
||||
avatar_url: null,
|
||||
role: 'user',
|
||||
balance: 10,
|
||||
concurrency: 2,
|
||||
status: 'active',
|
||||
allowed_groups: null,
|
||||
balance_notify_enabled: true,
|
||||
balance_notify_threshold: null,
|
||||
balance_notify_extra_emails: [],
|
||||
created_at: '2026-04-20T00:00:00Z',
|
||||
updated_at: '2026-04-20T00:00:00Z',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('ProfileInfoCard', () => {
|
||||
beforeEach(() => {
|
||||
updateProfileMock.mockReset()
|
||||
showSuccessMock.mockReset()
|
||||
showErrorMock.mockReset()
|
||||
authStoreState.user = null
|
||||
})
|
||||
|
||||
it('saves a remote avatar URL and updates the auth store', async () => {
|
||||
const updatedUser = createUser({ avatar_url: 'https://cdn.example.com/new.png' })
|
||||
updateProfileMock.mockResolvedValue(updatedUser)
|
||||
authStoreState.user = createUser()
|
||||
|
||||
const wrapper = mount(ProfileInfoCard, {
|
||||
props: {
|
||||
user: authStoreState.user
|
||||
},
|
||||
global: {
|
||||
stubs: {
|
||||
Icon: true,
|
||||
ProfileIdentityBindingsSection: true
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.get('[data-testid="profile-avatar-input"]').setValue('https://cdn.example.com/new.png')
|
||||
await wrapper.get('[data-testid="profile-avatar-save"]').trigger('click')
|
||||
|
||||
expect(updateProfileMock).toHaveBeenCalledWith({ avatar_url: 'https://cdn.example.com/new.png' })
|
||||
expect(authStoreState.user?.avatar_url).toBe('https://cdn.example.com/new.png')
|
||||
expect(showSuccessMock).toHaveBeenCalledWith('Avatar updated')
|
||||
})
|
||||
|
||||
it('rejects an oversized data URL before sending the request', async () => {
|
||||
authStoreState.user = createUser()
|
||||
const oversized = `data:image/png;base64,${Buffer.from(new Uint8Array(102401)).toString('base64')}`
|
||||
|
||||
const wrapper = mount(ProfileInfoCard, {
|
||||
props: {
|
||||
user: authStoreState.user
|
||||
},
|
||||
global: {
|
||||
stubs: {
|
||||
Icon: true,
|
||||
ProfileIdentityBindingsSection: true
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.get('[data-testid="profile-avatar-input"]').setValue(oversized)
|
||||
await wrapper.get('[data-testid="profile-avatar-save"]').trigger('click')
|
||||
|
||||
expect(updateProfileMock).not.toHaveBeenCalled()
|
||||
expect(showErrorMock).toHaveBeenCalledWith('Avatar image must be 100KB or smaller')
|
||||
})
|
||||
|
||||
it('deletes the current avatar', async () => {
|
||||
const updatedUser = createUser({ avatar_url: null })
|
||||
updateProfileMock.mockResolvedValue(updatedUser)
|
||||
authStoreState.user = createUser({ avatar_url: 'https://cdn.example.com/old.png' })
|
||||
|
||||
const wrapper = mount(ProfileInfoCard, {
|
||||
props: {
|
||||
user: authStoreState.user
|
||||
},
|
||||
global: {
|
||||
stubs: {
|
||||
Icon: true,
|
||||
ProfileIdentityBindingsSection: true
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.get('[data-testid="profile-avatar-delete"]').trigger('click')
|
||||
|
||||
expect(updateProfileMock).toHaveBeenCalledWith({ avatar_url: '' })
|
||||
expect(authStoreState.user?.avatar_url).toBeNull()
|
||||
expect(showSuccessMock).toHaveBeenCalledWith('Avatar removed')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user