feat: 头像上传/修改 + 个人资料连贯设置面板
- 头像:users.avatar 列 + POST /api/auth/avatar(OSS 上传/清除)+ toPublicUser 返回 avatar; user store updateAvatar + avatar 计算(自定义优先,ui-avatars 兜底) - 共享 saveImage 工具(admin 上传与头像复用,消除重复) - 个人资料布局:单一连贯设置面板(divide-y 分区:基本信息含头像编辑 / 安全设置 / 危险区), 去掉小卡片堆叠;i18n 头像键
This commit is contained in:
+79
-32
@@ -63,6 +63,37 @@ const saveProfile = async () => {
|
|||||||
: { ok: false, text: apiError({ data: { code: result.code } }) }
|
: { ok: false, text: apiError({ data: { code: result.code } }) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---------- 头像 ---------- */
|
||||||
|
const avatarUpdating = ref(false)
|
||||||
|
const avatarMsg = ref<{ ok: boolean; text: string } | null>(null)
|
||||||
|
const onAvatarChange = async (e: Event) => {
|
||||||
|
const input = e.target as HTMLInputElement
|
||||||
|
const file = input.files?.[0]
|
||||||
|
if (!file) return
|
||||||
|
if (!/^image\//.test(file.type) || file.size > 8 * 1024 * 1024) {
|
||||||
|
avatarMsg.value = { ok: false, text: t('account.avatar.error') }
|
||||||
|
input.value = ''
|
||||||
|
return
|
||||||
|
}
|
||||||
|
avatarUpdating.value = true
|
||||||
|
avatarMsg.value = null
|
||||||
|
const result = await userStore.updateAvatar(file)
|
||||||
|
avatarUpdating.value = false
|
||||||
|
input.value = ''
|
||||||
|
avatarMsg.value = result.success
|
||||||
|
? { ok: true, text: t('account.avatar.success') }
|
||||||
|
: { ok: false, text: t('account.avatar.error') }
|
||||||
|
}
|
||||||
|
const removeAvatar = async () => {
|
||||||
|
avatarUpdating.value = true
|
||||||
|
avatarMsg.value = null
|
||||||
|
const result = await userStore.updateAvatar(null)
|
||||||
|
avatarUpdating.value = false
|
||||||
|
avatarMsg.value = result.success
|
||||||
|
? { ok: true, text: t('account.avatar.success') }
|
||||||
|
: { ok: false, text: t('account.avatar.error') }
|
||||||
|
}
|
||||||
|
|
||||||
/* ---------- 修改密码 ---------- */
|
/* ---------- 修改密码 ---------- */
|
||||||
const pwForm = reactive({ currentPassword: '', newPassword: '', confirmPassword: '' })
|
const pwForm = reactive({ currentPassword: '', newPassword: '', confirmPassword: '' })
|
||||||
const pwSaving = ref(false)
|
const pwSaving = ref(false)
|
||||||
@@ -272,15 +303,41 @@ onBeforeUnmount(() => ctx?.revert())
|
|||||||
<!-- 内容 -->
|
<!-- 内容 -->
|
||||||
<div class="mt-8 md:mt-10">
|
<div class="mt-8 md:mt-10">
|
||||||
<Transition name="panel" mode="out-in">
|
<Transition name="panel" mode="out-in">
|
||||||
<!-- 个人资料 -->
|
<!-- 个人资料(单一设置面板,内部分区) -->
|
||||||
<section v-if="activeTab === 'profile'" key="profile" class="space-y-6 max-w-2xl mx-auto">
|
<section v-if="activeTab === 'profile'" key="profile" class="max-w-2xl mx-auto">
|
||||||
<!-- 资料编辑 -->
|
<div class="rounded-3xl border border-gray-100 bg-white shadow-sm overflow-hidden divide-y divide-gray-100">
|
||||||
<div class="rounded-2xl border border-gray-100 bg-white shadow-sm overflow-hidden">
|
<!-- 基本信息 -->
|
||||||
<div class="px-6 md:px-8 py-5 border-b border-gray-100">
|
<div class="px-6 md:px-8 py-7">
|
||||||
<h3 class="text-lg font-bold text-black">{{ t('account.profile') }}</h3>
|
<h3 class="text-lg font-bold text-black">{{ t('account.profile') }}</h3>
|
||||||
<p class="text-sm text-gray-400 mt-0.5">个人基本信息</p>
|
<p class="text-sm text-gray-400 mt-0.5">个人基本信息与头像</p>
|
||||||
|
|
||||||
|
<div class="mt-6 flex items-center gap-6">
|
||||||
|
<img :src="userStore.avatar" :alt="userStore.user?.username"
|
||||||
|
class="w-20 h-20 rounded-2xl object-cover ring-1 ring-black/10 flex-shrink-0" />
|
||||||
|
<div class="space-y-2.5">
|
||||||
|
<label class="inline-flex cursor-pointer">
|
||||||
|
<input type="file" accept="image/*" class="hidden" @change="onAvatarChange" />
|
||||||
|
<span
|
||||||
|
class="inline-flex items-center gap-1.5 px-4 py-2 rounded-full border border-gray-200 text-sm font-semibold text-gray-700 hover:border-black hover:text-black transition-colors"
|
||||||
|
>
|
||||||
|
<Icon v-if="avatarUpdating" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
|
||||||
|
<Icon v-else name="ph:camera" class="w-4 h-4" />
|
||||||
|
{{ t('account.avatar.change') }}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
v-if="userStore.user?.avatar"
|
||||||
|
@click="removeAvatar"
|
||||||
|
:disabled="avatarUpdating"
|
||||||
|
class="block text-sm text-gray-400 hover:text-red-600 transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{{ t('account.avatar.remove') }}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="px-6 md:px-8 py-6 space-y-5">
|
</div>
|
||||||
|
<p v-if="avatarMsg" class="mt-3 text-sm" :class="avatarMsg.ok ? 'text-green-600' : 'text-red-600'">{{ avatarMsg.text }}</p>
|
||||||
|
|
||||||
|
<div class="mt-7 space-y-5">
|
||||||
<div>
|
<div>
|
||||||
<label class="block text-sm font-semibold text-gray-800 mb-1.5">{{ t('account.username') }}</label>
|
<label class="block text-sm font-semibold text-gray-800 mb-1.5">{{ t('account.username') }}</label>
|
||||||
<input v-model="profileForm.username" type="text"
|
<input v-model="profileForm.username" type="text"
|
||||||
@@ -298,11 +355,8 @@ onBeforeUnmount(() => ctx?.revert())
|
|||||||
</div>
|
</div>
|
||||||
<p v-if="profileMsg" class="text-sm" :class="profileMsg.ok ? 'text-green-600' : 'text-red-600'">{{ profileMsg.text }}</p>
|
<p v-if="profileMsg" class="text-sm" :class="profileMsg.ok ? 'text-green-600' : 'text-red-600'">{{ profileMsg.text }}</p>
|
||||||
<div class="flex justify-end">
|
<div class="flex justify-end">
|
||||||
<button
|
<button @click="saveProfile" :disabled="profileSaving"
|
||||||
@click="saveProfile"
|
class="inline-flex items-center gap-2 px-6 py-2.5 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors disabled:opacity-50">
|
||||||
:disabled="profileSaving"
|
|
||||||
class="inline-flex items-center gap-2 px-6 py-2.5 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors disabled:opacity-50"
|
|
||||||
>
|
|
||||||
<Icon v-if="profileSaving" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
|
<Icon v-if="profileSaving" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
|
||||||
{{ profileSaving ? t('account.saving') : t('account.save') }}
|
{{ profileSaving ? t('account.saving') : t('account.save') }}
|
||||||
</button>
|
</button>
|
||||||
@@ -310,18 +364,17 @@ onBeforeUnmount(() => ctx?.revert())
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 修改密码 -->
|
<!-- 安全设置 -->
|
||||||
<div class="rounded-2xl border border-gray-100 bg-white shadow-sm overflow-hidden">
|
<div class="px-6 md:px-8 py-7">
|
||||||
<div class="px-6 md:px-8 py-5 border-b border-gray-100">
|
|
||||||
<h3 class="text-lg font-bold text-black">{{ t('account.changePassword.title') }}</h3>
|
<h3 class="text-lg font-bold text-black">{{ t('account.changePassword.title') }}</h3>
|
||||||
<p class="text-sm text-gray-400 mt-0.5">定期更换密码更安全</p>
|
<p class="text-sm text-gray-400 mt-0.5">定期更换密码更安全</p>
|
||||||
</div>
|
<form class="mt-6 space-y-5" @submit.prevent="changePassword">
|
||||||
<form class="px-6 md:px-8 py-6 space-y-5" @submit.prevent="changePassword">
|
|
||||||
<div>
|
<div>
|
||||||
<label class="block text-sm font-semibold text-gray-800 mb-1.5">{{ t('account.changePassword.currentPassword') }}</label>
|
<label class="block text-sm font-semibold text-gray-800 mb-1.5">{{ t('account.changePassword.currentPassword') }}</label>
|
||||||
<input v-model="pwForm.currentPassword" type="password" autocomplete="current-password" required
|
<input v-model="pwForm.currentPassword" type="password" autocomplete="current-password" required
|
||||||
class="w-full rounded-xl border border-gray-200 bg-white px-3.5 py-2.5 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10" />
|
class="w-full rounded-xl border border-gray-200 bg-white px-3.5 py-2.5 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10" />
|
||||||
</div>
|
</div>
|
||||||
|
<div class="grid grid-cols-1 sm:grid-cols-2 gap-5">
|
||||||
<div>
|
<div>
|
||||||
<label class="block text-sm font-semibold text-gray-800 mb-1.5">{{ t('account.changePassword.newPassword') }}</label>
|
<label class="block text-sm font-semibold text-gray-800 mb-1.5">{{ t('account.changePassword.newPassword') }}</label>
|
||||||
<input v-model="pwForm.newPassword" type="password" autocomplete="new-password" required
|
<input v-model="pwForm.newPassword" type="password" autocomplete="new-password" required
|
||||||
@@ -332,14 +385,12 @@ onBeforeUnmount(() => ctx?.revert())
|
|||||||
<input v-model="pwForm.confirmPassword" type="password" autocomplete="new-password" required
|
<input v-model="pwForm.confirmPassword" type="password" autocomplete="new-password" required
|
||||||
class="w-full rounded-xl border border-gray-200 bg-white px-3.5 py-2.5 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10" />
|
class="w-full rounded-xl border border-gray-200 bg-white px-3.5 py-2.5 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10" />
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
<p v-if="pwError" class="text-sm text-red-600">{{ pwError }}</p>
|
<p v-if="pwError" class="text-sm text-red-600">{{ pwError }}</p>
|
||||||
<p v-if="pwOk" class="text-sm text-green-600">{{ t('account.changePassword.success') }}</p>
|
<p v-if="pwOk" class="text-sm text-green-600">{{ t('account.changePassword.success') }}</p>
|
||||||
<div class="flex justify-end">
|
<div class="flex justify-end">
|
||||||
<button
|
<button type="submit" :disabled="pwSaving"
|
||||||
type="submit"
|
class="inline-flex items-center gap-2 px-6 py-2.5 rounded-full border border-gray-200 text-gray-700 text-sm font-semibold hover:border-black hover:text-black transition-colors disabled:opacity-50">
|
||||||
:disabled="pwSaving"
|
|
||||||
class="inline-flex items-center gap-2 px-6 py-2.5 rounded-full border border-gray-200 text-gray-700 text-sm font-semibold hover:border-black hover:text-black transition-colors disabled:opacity-50"
|
|
||||||
>
|
|
||||||
<Icon v-if="pwSaving" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
|
<Icon v-if="pwSaving" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
|
||||||
{{ pwSaving ? t('account.changePassword.saving') : t('account.changePassword.submit') }}
|
{{ pwSaving ? t('account.changePassword.saving') : t('account.changePassword.submit') }}
|
||||||
</button>
|
</button>
|
||||||
@@ -347,13 +398,11 @@ onBeforeUnmount(() => ctx?.revert())
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 删除账号(克制危险区) -->
|
<!-- 危险操作 -->
|
||||||
<div class="rounded-2xl border border-red-200 bg-red-50/40 overflow-hidden">
|
<div class="px-6 md:px-8 py-7 bg-red-50/40">
|
||||||
<div class="px-6 md:px-8 py-5 border-b border-red-100">
|
|
||||||
<h3 class="text-lg font-bold text-red-600">{{ t('account.deleteAccount.title') }}</h3>
|
<h3 class="text-lg font-bold text-red-600">{{ t('account.deleteAccount.title') }}</h3>
|
||||||
<p class="text-sm text-red-400 mt-0.5">危险操作</p>
|
<p class="text-sm text-red-400 mt-0.5">危险操作</p>
|
||||||
</div>
|
<div class="mt-6 space-y-5">
|
||||||
<div class="px-6 md:px-8 py-6 space-y-5">
|
|
||||||
<p class="text-sm text-gray-600 leading-relaxed">{{ t('account.deleteAccount.hint') }}</p>
|
<p class="text-sm text-gray-600 leading-relaxed">{{ t('account.deleteAccount.hint') }}</p>
|
||||||
<div>
|
<div>
|
||||||
<label class="block text-sm font-semibold text-gray-800 mb-1.5">{{ t('auth.password') }}</label>
|
<label class="block text-sm font-semibold text-gray-800 mb-1.5">{{ t('auth.password') }}</label>
|
||||||
@@ -364,17 +413,15 @@ onBeforeUnmount(() => ctx?.revert())
|
|||||||
</div>
|
</div>
|
||||||
<p v-if="deleteError" class="text-sm text-red-600">{{ deleteError }}</p>
|
<p v-if="deleteError" class="text-sm text-red-600">{{ deleteError }}</p>
|
||||||
<div class="flex justify-end">
|
<div class="flex justify-end">
|
||||||
<button
|
<button @click="askDeleteAccount" :disabled="deleting"
|
||||||
@click="askDeleteAccount"
|
class="inline-flex items-center gap-2 px-6 py-2.5 rounded-full bg-red-600 text-white text-sm font-semibold hover:bg-red-700 transition-colors disabled:opacity-50">
|
||||||
:disabled="deleting"
|
|
||||||
class="inline-flex items-center gap-2 px-6 py-2.5 rounded-full bg-red-600 text-white text-sm font-semibold hover:bg-red-700 transition-colors disabled:opacity-50"
|
|
||||||
>
|
|
||||||
<Icon v-if="deleting" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
|
<Icon v-if="deleting" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
|
||||||
{{ t('account.deleteAccount.confirmButton') }}
|
{{ t('account.deleteAccount.confirmButton') }}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 我的收藏 -->
|
<!-- 我的收藏 -->
|
||||||
|
|||||||
+25
-2
@@ -6,6 +6,7 @@ export interface User {
|
|||||||
username: string
|
username: string
|
||||||
email: string
|
email: string
|
||||||
phone: string | null
|
phone: string | null
|
||||||
|
avatar: string | null
|
||||||
role: 'user' | 'admin'
|
role: 'user' | 'admin'
|
||||||
createdAt: string
|
createdAt: string
|
||||||
}
|
}
|
||||||
@@ -90,8 +91,29 @@ export const useUserStore = defineStore('user', () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 头像(按用户名生成,无后端存储)
|
// 更新头像(上传后由接口返回新 user,直接替换)
|
||||||
const avatar = computed(() => (user.value ? AVATAR_URL(user.value.username) : ''))
|
const updateAvatar = async (file: File | null): Promise<ApiResult> => {
|
||||||
|
try {
|
||||||
|
if (file) {
|
||||||
|
const fd = new FormData()
|
||||||
|
fd.append('file', file)
|
||||||
|
const data = await $fetch<{ user: User }>('/api/auth/avatar', { method: 'POST', body: fd })
|
||||||
|
user.value = data.user
|
||||||
|
} else {
|
||||||
|
const data = await $fetch<{ user: User }>('/api/auth/avatar', { method: 'POST', body: { clear: true } })
|
||||||
|
user.value = data.user
|
||||||
|
}
|
||||||
|
return { success: true }
|
||||||
|
} catch (err) {
|
||||||
|
return { success: false, code: (err as any)?.data?.code || 'SERVER_ERROR' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 头像:用户自定义优先,否则按用户名生成
|
||||||
|
const avatar = computed(() => {
|
||||||
|
if (!user.value) return ''
|
||||||
|
return user.value.avatar || AVATAR_URL(user.value.username)
|
||||||
|
})
|
||||||
|
|
||||||
return {
|
return {
|
||||||
user,
|
user,
|
||||||
@@ -102,5 +124,6 @@ export const useUserStore = defineStore('user', () => {
|
|||||||
logout,
|
logout,
|
||||||
restoreUser,
|
restoreUser,
|
||||||
updateProfile,
|
updateProfile,
|
||||||
|
updateAvatar,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -453,7 +453,14 @@
|
|||||||
},
|
},
|
||||||
"statFavorites": "Favorites",
|
"statFavorites": "Favorites",
|
||||||
"statComments": "Comments",
|
"statComments": "Comments",
|
||||||
"statJoined": "Joined"
|
"statJoined": "Joined",
|
||||||
|
"avatar": {
|
||||||
|
"change": "Change Avatar",
|
||||||
|
"uploading": "Uploading...",
|
||||||
|
"remove": "Remove Avatar",
|
||||||
|
"error": "Failed to update avatar",
|
||||||
|
"success": "Avatar updated"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"comments": {
|
"comments": {
|
||||||
"title": "Comments",
|
"title": "Comments",
|
||||||
|
|||||||
@@ -453,7 +453,14 @@
|
|||||||
},
|
},
|
||||||
"statFavorites": "收藏",
|
"statFavorites": "收藏",
|
||||||
"statComments": "评论",
|
"statComments": "评论",
|
||||||
"statJoined": "加入于"
|
"statJoined": "加入于",
|
||||||
|
"avatar": {
|
||||||
|
"change": "更换头像",
|
||||||
|
"uploading": "上传中...",
|
||||||
|
"remove": "移除头像",
|
||||||
|
"error": "头像更新失败",
|
||||||
|
"success": "头像已更新"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"comments": {
|
"comments": {
|
||||||
"title": "评论",
|
"title": "评论",
|
||||||
|
|||||||
@@ -1,26 +1,10 @@
|
|||||||
import { readMultipartFormData, createError } from 'h3'
|
import { readMultipartFormData, createError } from 'h3'
|
||||||
import { writeFileSync, mkdirSync } from 'node:fs'
|
|
||||||
import { dirname, join } from 'node:path'
|
|
||||||
import { randomBytes } from 'node:crypto'
|
|
||||||
import { requireAdmin } from '../../utils/auth'
|
import { requireAdmin } from '../../utils/auth'
|
||||||
import { getConfig } from '../../utils/config'
|
import { saveImage, IMAGE_EXT_BY_TYPE, UploadError } from '../../utils/upload'
|
||||||
import { getOssConfig, putObject } from '../../utils/s3'
|
|
||||||
import { writeAudit } from '../../utils/audit'
|
import { writeAudit } from '../../utils/audit'
|
||||||
|
|
||||||
const MAX_SIZE = 8 * 1024 * 1024 // 8MB
|
|
||||||
const EXT_BY_TYPE: Record<string, string> = {
|
|
||||||
'image/png': 'png',
|
|
||||||
'image/jpeg': 'jpg',
|
|
||||||
'image/gif': 'gif',
|
|
||||||
'image/webp': 'webp',
|
|
||||||
'image/svg+xml': 'svg',
|
|
||||||
'image/avif': 'avif',
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 后台图片上传:
|
* 后台图片上传:走 OSS(未配置时本地回退),返回 /uploads/<folder>/<name>
|
||||||
* - OSS 已配置 -> 上传到桶 arcticnewone(key: images/<name>),URL /uploads/images/<name>
|
|
||||||
* - OSS 未配置 -> 回退写入本地 /data/uploads(兼容无 OSS 环境)
|
|
||||||
*/
|
*/
|
||||||
export default defineEventHandler(async (event) => {
|
export default defineEventHandler(async (event) => {
|
||||||
requireAdmin(event)
|
requireAdmin(event)
|
||||||
@@ -30,30 +14,21 @@ export default defineEventHandler(async (event) => {
|
|||||||
if (!file || !file.data) {
|
if (!file || !file.data) {
|
||||||
throw createError({ statusCode: 400, message: '缺少文件', data: { code: 'VALIDATION_ERROR' } })
|
throw createError({ statusCode: 400, message: '缺少文件', data: { code: 'VALIDATION_ERROR' } })
|
||||||
}
|
}
|
||||||
|
const type = file.type || ''
|
||||||
const type = file.type || 'application/octet-stream'
|
if (!IMAGE_EXT_BY_TYPE[type]) {
|
||||||
const ext = EXT_BY_TYPE[type]
|
|
||||||
if (!ext) {
|
|
||||||
throw createError({ statusCode: 400, message: '仅支持图片(png/jpg/gif/webp/svg/avif)', data: { code: 'VALIDATION_ERROR' } })
|
throw createError({ statusCode: 400, message: '仅支持图片(png/jpg/gif/webp/svg/avif)', data: { code: 'VALIDATION_ERROR' } })
|
||||||
}
|
}
|
||||||
if (file.data.length > MAX_SIZE) {
|
|
||||||
throw createError({ statusCode: 400, message: '文件过大(上限 8MB)', data: { code: 'VALIDATION_ERROR' } })
|
let url: string
|
||||||
|
try {
|
||||||
|
url = await saveImage(Buffer.from(file.data), type, 'images')
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof UploadError) {
|
||||||
|
throw createError({ statusCode: 400, message: err.message, data: { code: 'VALIDATION_ERROR' } })
|
||||||
|
}
|
||||||
|
throw err
|
||||||
}
|
}
|
||||||
|
|
||||||
const name = `${Date.now()}-${randomBytes(6).toString('hex')}.${ext}`
|
writeAudit(event, 'upload', `oss:${url}`)
|
||||||
|
return { ok: true, url }
|
||||||
const oss = getOssConfig()
|
|
||||||
if (oss) {
|
|
||||||
const key = `images/${name}`
|
|
||||||
await putObject(key, Buffer.from(file.data), type)
|
|
||||||
writeAudit(event, 'upload', `oss:${key}`)
|
|
||||||
return { ok: true, url: `/uploads/images/${name}` }
|
|
||||||
}
|
|
||||||
|
|
||||||
// 本地回退(保留历史行为,兼容无 OSS 环境)
|
|
||||||
const dir = join(dirname(getConfig().dbPath), 'uploads')
|
|
||||||
mkdirSync(dir, { recursive: true })
|
|
||||||
writeFileSync(join(dir, name), Buffer.from(file.data))
|
|
||||||
writeAudit(event, 'upload', `local:${name}`)
|
|
||||||
return { ok: true, url: `/uploads/${name}` }
|
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { readMultipartFormData, readBody, createError } from 'h3'
|
||||||
|
import { requireUser, toPublicUser, type UserRow } from '../../utils/auth'
|
||||||
|
import { getDb } from '../../utils/db'
|
||||||
|
import { saveImage, IMAGE_EXT_BY_TYPE, UploadError } from '../../utils/upload'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 修改头像:
|
||||||
|
* - multipart/form-data(字段 file)-> 上传图片到 OSS/本地,保存 URL
|
||||||
|
* - JSON { clear: true } -> 清除头像(回退默认生成头像)
|
||||||
|
*/
|
||||||
|
export default defineEventHandler(async (event) => {
|
||||||
|
const user = requireUser(event)
|
||||||
|
const db = getDb()
|
||||||
|
const contentType = event.headers.get('content-type') || ''
|
||||||
|
|
||||||
|
if (contentType.includes('multipart/form-data')) {
|
||||||
|
const parts = await readMultipartFormData(event)
|
||||||
|
const file = parts?.find((p) => p.name === 'file' && p.data?.length)
|
||||||
|
if (!file?.data) {
|
||||||
|
throw createError({ statusCode: 400, message: '缺少文件', data: { code: 'VALIDATION_ERROR' } })
|
||||||
|
}
|
||||||
|
const type = file.type || ''
|
||||||
|
if (!IMAGE_EXT_BY_TYPE[type]) {
|
||||||
|
throw createError({ statusCode: 400, message: '仅支持图片(png/jpg/gif/webp/svg/avif)', data: { code: 'VALIDATION_ERROR' } })
|
||||||
|
}
|
||||||
|
|
||||||
|
let url: string
|
||||||
|
try {
|
||||||
|
url = await saveImage(Buffer.from(file.data), type, 'avatars')
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof UploadError) {
|
||||||
|
throw createError({ statusCode: 400, message: err.message, data: { code: 'VALIDATION_ERROR' } })
|
||||||
|
}
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
|
||||||
|
db.prepare('UPDATE users SET avatar = ? WHERE id = ?').run(url, user.id)
|
||||||
|
const updated = db
|
||||||
|
.prepare('SELECT id, username, email, phone, avatar, role, created_at FROM users WHERE id = ?')
|
||||||
|
.get(user.id) as UserRow
|
||||||
|
return { ok: true, user: toPublicUser(updated) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// JSON:清除头像
|
||||||
|
const body = await readBody(event).catch(() => ({}))
|
||||||
|
if (body?.clear) {
|
||||||
|
db.prepare('UPDATE users SET avatar = NULL WHERE id = ?').run(user.id)
|
||||||
|
} else {
|
||||||
|
throw createError({ statusCode: 400, message: '请上传图片或传入 clear', data: { code: 'VALIDATION_ERROR' } })
|
||||||
|
}
|
||||||
|
const updated = db
|
||||||
|
.prepare('SELECT id, username, email, phone, avatar, role, created_at FROM users WHERE id = ?')
|
||||||
|
.get(user.id) as UserRow
|
||||||
|
return { ok: true, user: toPublicUser(updated) }
|
||||||
|
})
|
||||||
@@ -11,6 +11,7 @@ export interface UserRow {
|
|||||||
username: string
|
username: string
|
||||||
email: string
|
email: string
|
||||||
phone: string | null
|
phone: string | null
|
||||||
|
avatar: string | null
|
||||||
role: 'user' | 'admin'
|
role: 'user' | 'admin'
|
||||||
created_at: string
|
created_at: string
|
||||||
}
|
}
|
||||||
@@ -38,7 +39,7 @@ export function getSessionUser(token: string | null): UserRow | null {
|
|||||||
if (!token) return null
|
if (!token) return null
|
||||||
const row = getDb()
|
const row = getDb()
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT u.id, u.username, u.email, u.phone, u.role, u.created_at
|
`SELECT u.id, u.username, u.email, u.phone, u.avatar, u.role, u.created_at
|
||||||
FROM sessions s
|
FROM sessions s
|
||||||
JOIN users u ON u.id = s.user_id
|
JOIN users u ON u.id = s.user_id
|
||||||
WHERE s.token = ? AND s.expires_at > datetime('now')`,
|
WHERE s.token = ? AND s.expires_at > datetime('now')`,
|
||||||
@@ -94,6 +95,7 @@ export function toPublicUser(user: UserRow): {
|
|||||||
username: string
|
username: string
|
||||||
email: string
|
email: string
|
||||||
phone: string | null
|
phone: string | null
|
||||||
|
avatar: string | null
|
||||||
role: 'user' | 'admin'
|
role: 'user' | 'admin'
|
||||||
createdAt: string
|
createdAt: string
|
||||||
} {
|
} {
|
||||||
@@ -102,6 +104,7 @@ export function toPublicUser(user: UserRow): {
|
|||||||
username: user.username,
|
username: user.username,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
phone: user.phone,
|
phone: user.phone,
|
||||||
|
avatar: user.avatar,
|
||||||
role: user.role,
|
role: user.role,
|
||||||
createdAt: user.created_at,
|
createdAt: user.created_at,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ function migrate(db: Database.Database): void {
|
|||||||
username TEXT NOT NULL UNIQUE,
|
username TEXT NOT NULL UNIQUE,
|
||||||
email TEXT NOT NULL UNIQUE,
|
email TEXT NOT NULL UNIQUE,
|
||||||
phone TEXT,
|
phone TEXT,
|
||||||
|
avatar TEXT,
|
||||||
password_hash TEXT NOT NULL,
|
password_hash TEXT NOT NULL,
|
||||||
role TEXT NOT NULL DEFAULT 'user',
|
role TEXT NOT NULL DEFAULT 'user',
|
||||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
@@ -178,6 +179,7 @@ function migrate(db: Database.Database): void {
|
|||||||
// 老库迁移:为已存在的表补充新增列(SQLite 不支持 ADD COLUMN IF NOT EXISTS)
|
// 老库迁移:为已存在的表补充新增列(SQLite 不支持 ADD COLUMN IF NOT EXISTS)
|
||||||
ensureColumn(db, 'contacts', 'read', 'INTEGER NOT NULL DEFAULT 0')
|
ensureColumn(db, 'contacts', 'read', 'INTEGER NOT NULL DEFAULT 0')
|
||||||
ensureColumn(db, 'subscribers', 'token', 'TEXT')
|
ensureColumn(db, 'subscribers', 'token', 'TEXT')
|
||||||
|
ensureColumn(db, 'users', 'avatar', 'TEXT')
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 若表中缺少某列则补上(用于老库升级) */
|
/** 若表中缺少某列则补上(用于老库升级) */
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { randomBytes } from 'node:crypto'
|
||||||
|
import { writeFileSync, mkdirSync } from 'node:fs'
|
||||||
|
import { dirname, join } from 'node:path'
|
||||||
|
import { getConfig } from './config'
|
||||||
|
import { getOssConfig, putObject } from './s3'
|
||||||
|
|
||||||
|
export const UPLOAD_MAX_SIZE = 8 * 1024 * 1024 // 8MB
|
||||||
|
|
||||||
|
export const IMAGE_EXT_BY_TYPE: Record<string, string> = {
|
||||||
|
'image/png': 'png',
|
||||||
|
'image/jpeg': 'jpg',
|
||||||
|
'image/gif': 'gif',
|
||||||
|
'image/webp': 'webp',
|
||||||
|
'image/svg+xml': 'svg',
|
||||||
|
'image/avif': 'avif',
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UploadError extends Error {
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存图片并返回访问 URL。
|
||||||
|
* - OSS 已配置 -> 上传到桶(key: <folder>/<name>),URL /uploads/<folder>/<name>
|
||||||
|
* - OSS 未配置 -> 存本地 /data/uploads/<folder>/<name>,URL 同上
|
||||||
|
*/
|
||||||
|
export async function saveImage(data: Buffer, type: string, folder: string): Promise<string> {
|
||||||
|
const ext = IMAGE_EXT_BY_TYPE[type]
|
||||||
|
if (!ext) {
|
||||||
|
throw new UploadError('仅支持图片(png/jpg/gif/webp/svg/avif)')
|
||||||
|
}
|
||||||
|
if (data.length > UPLOAD_MAX_SIZE) {
|
||||||
|
throw new UploadError('文件过大(上限 8MB)')
|
||||||
|
}
|
||||||
|
|
||||||
|
const name = `${Date.now()}-${randomBytes(6).toString('hex')}.${ext}`
|
||||||
|
const oss = getOssConfig()
|
||||||
|
if (oss) {
|
||||||
|
const key = `${folder}/${name}`
|
||||||
|
await putObject(key, data, type)
|
||||||
|
return `/uploads/${key}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const dir = join(dirname(getConfig().dbPath), 'uploads', folder)
|
||||||
|
mkdirSync(dir, { recursive: true })
|
||||||
|
writeFileSync(join(dir, name), data)
|
||||||
|
return `/uploads/${folder}/${name}`
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user