From b9ffcdb8740e226f659ddc82e13794382a8c0344 Mon Sep 17 00:00:00 2001 From: chenchun Date: Thu, 6 Aug 2026 19:40:41 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A4=B4=E5=83=8F=E4=B8=8A=E4=BC=A0/?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=20+=20=E4=B8=AA=E4=BA=BA=E8=B5=84=E6=96=99?= =?UTF-8?q?=E8=BF=9E=E8=B4=AF=E8=AE=BE=E7=BD=AE=E9=9D=A2=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 头像:users.avatar 列 + POST /api/auth/avatar(OSS 上传/清除)+ toPublicUser 返回 avatar; user store updateAvatar + avatar 计算(自定义优先,ui-avatars 兜底) - 共享 saveImage 工具(admin 上传与头像复用,消除重复) - 个人资料布局:单一连贯设置面板(divide-y 分区:基本信息含头像编辑 / 安全设置 / 危险区), 去掉小卡片堆叠;i18n 头像键 --- app/pages/account.vue | 231 +++++++++++++++++++------------- app/stores/user.ts | 27 +++- i18n/locales/en.json | 9 +- i18n/locales/zh.json | 9 +- server/api/admin/upload.post.ts | 55 +++----- server/api/auth/avatar.post.ts | 55 ++++++++ server/utils/auth.ts | 5 +- server/utils/db.ts | 2 + server/utils/upload.ts | 50 +++++++ 9 files changed, 306 insertions(+), 137 deletions(-) create mode 100644 server/api/auth/avatar.post.ts create mode 100644 server/utils/upload.ts diff --git a/app/pages/account.vue b/app/pages/account.vue index 070b183..5f4da4e 100644 --- a/app/pages/account.vue +++ b/app/pages/account.vue @@ -63,6 +63,37 @@ const saveProfile = async () => { : { 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 pwSaving = ref(false) @@ -272,106 +303,122 @@ onBeforeUnmount(() => ctx?.revert())
- -
- -
-
+ +
+
+ +

{{ t('account.profile') }}

-

个人基本信息

-
-
-
- - -
-
- - -
-
- - -
-

{{ profileMsg.text }}

-
- -
-
-
+

个人基本信息与头像

- -
-
+
+ +
+ + +
+
+

{{ avatarMsg.text }}

+ +
+
+ + +
+
+ + +
+
+ + +
+

{{ profileMsg.text }}

+
+ +
+
+
+ + +

{{ t('account.changePassword.title') }}

定期更换密码更安全

+
+
+ + +
+
+
+ + +
+
+ + +
+
+

{{ pwError }}

+

{{ t('account.changePassword.success') }}

+
+ +
+
-
-
- - -
-
- - -
-
- - -
-

{{ pwError }}

-

{{ t('account.changePassword.success') }}

-
- -
-
-
- -
-
+ +

{{ t('account.deleteAccount.title') }}

危险操作

-
-
-

{{ t('account.deleteAccount.hint') }}

-
- - -
-

{{ deleteError }}

-
- +
+

{{ t('account.deleteAccount.hint') }}

+
+ + +
+

{{ deleteError }}

+
+ +
diff --git a/app/stores/user.ts b/app/stores/user.ts index c04b1f9..247d53b 100644 --- a/app/stores/user.ts +++ b/app/stores/user.ts @@ -6,6 +6,7 @@ export interface User { username: string email: string phone: string | null + avatar: string | null role: 'user' | 'admin' createdAt: string } @@ -90,8 +91,29 @@ export const useUserStore = defineStore('user', () => { } } - // 头像(按用户名生成,无后端存储) - const avatar = computed(() => (user.value ? AVATAR_URL(user.value.username) : '')) + // 更新头像(上传后由接口返回新 user,直接替换) + const updateAvatar = async (file: File | null): Promise => { + 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 { user, @@ -102,5 +124,6 @@ export const useUserStore = defineStore('user', () => { logout, restoreUser, updateProfile, + updateAvatar, } }) diff --git a/i18n/locales/en.json b/i18n/locales/en.json index 9063e9a..a1db67f 100755 --- a/i18n/locales/en.json +++ b/i18n/locales/en.json @@ -453,7 +453,14 @@ }, "statFavorites": "Favorites", "statComments": "Comments", - "statJoined": "Joined" + "statJoined": "Joined", + "avatar": { + "change": "Change Avatar", + "uploading": "Uploading...", + "remove": "Remove Avatar", + "error": "Failed to update avatar", + "success": "Avatar updated" + } }, "comments": { "title": "Comments", diff --git a/i18n/locales/zh.json b/i18n/locales/zh.json index c64b12f..3e61fcd 100755 --- a/i18n/locales/zh.json +++ b/i18n/locales/zh.json @@ -453,7 +453,14 @@ }, "statFavorites": "收藏", "statComments": "评论", - "statJoined": "加入于" + "statJoined": "加入于", + "avatar": { + "change": "更换头像", + "uploading": "上传中...", + "remove": "移除头像", + "error": "头像更新失败", + "success": "头像已更新" + } }, "comments": { "title": "评论", diff --git a/server/api/admin/upload.post.ts b/server/api/admin/upload.post.ts index f6aad01..e37e0c3 100644 --- a/server/api/admin/upload.post.ts +++ b/server/api/admin/upload.post.ts @@ -1,26 +1,10 @@ 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 { getConfig } from '../../utils/config' -import { getOssConfig, putObject } from '../../utils/s3' +import { saveImage, IMAGE_EXT_BY_TYPE, UploadError } from '../../utils/upload' import { writeAudit } from '../../utils/audit' -const MAX_SIZE = 8 * 1024 * 1024 // 8MB -const EXT_BY_TYPE: Record = { - 'image/png': 'png', - 'image/jpeg': 'jpg', - 'image/gif': 'gif', - 'image/webp': 'webp', - 'image/svg+xml': 'svg', - 'image/avif': 'avif', -} - /** - * 后台图片上传: - * - OSS 已配置 -> 上传到桶 arcticnewone(key: images/),URL /uploads/images/ - * - OSS 未配置 -> 回退写入本地 /data/uploads(兼容无 OSS 环境) + * 后台图片上传:走 OSS(未配置时本地回退),返回 /uploads// */ export default defineEventHandler(async (event) => { requireAdmin(event) @@ -30,30 +14,21 @@ export default defineEventHandler(async (event) => { if (!file || !file.data) { throw createError({ statusCode: 400, message: '缺少文件', data: { code: 'VALIDATION_ERROR' } }) } - - const type = file.type || 'application/octet-stream' - const ext = EXT_BY_TYPE[type] - if (!ext) { + 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' } }) } - 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}` - - 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}` } + writeAudit(event, 'upload', `oss:${url}`) + return { ok: true, url } }) diff --git a/server/api/auth/avatar.post.ts b/server/api/auth/avatar.post.ts new file mode 100644 index 0000000..33cb5d5 --- /dev/null +++ b/server/api/auth/avatar.post.ts @@ -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) } +}) diff --git a/server/utils/auth.ts b/server/utils/auth.ts index 90392ea..310d53e 100644 --- a/server/utils/auth.ts +++ b/server/utils/auth.ts @@ -11,6 +11,7 @@ export interface UserRow { username: string email: string phone: string | null + avatar: string | null role: 'user' | 'admin' created_at: string } @@ -38,7 +39,7 @@ export function getSessionUser(token: string | null): UserRow | null { if (!token) return null const row = getDb() .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 JOIN users u ON u.id = s.user_id WHERE s.token = ? AND s.expires_at > datetime('now')`, @@ -94,6 +95,7 @@ export function toPublicUser(user: UserRow): { username: string email: string phone: string | null + avatar: string | null role: 'user' | 'admin' createdAt: string } { @@ -102,6 +104,7 @@ export function toPublicUser(user: UserRow): { username: user.username, email: user.email, phone: user.phone, + avatar: user.avatar, role: user.role, createdAt: user.created_at, } diff --git a/server/utils/db.ts b/server/utils/db.ts index 6d751c3..4e59765 100644 --- a/server/utils/db.ts +++ b/server/utils/db.ts @@ -49,6 +49,7 @@ function migrate(db: Database.Database): void { username TEXT NOT NULL UNIQUE, email TEXT NOT NULL UNIQUE, phone TEXT, + avatar TEXT, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'user', created_at TEXT NOT NULL DEFAULT (datetime('now')) @@ -178,6 +179,7 @@ function migrate(db: Database.Database): void { // 老库迁移:为已存在的表补充新增列(SQLite 不支持 ADD COLUMN IF NOT EXISTS) ensureColumn(db, 'contacts', 'read', 'INTEGER NOT NULL DEFAULT 0') ensureColumn(db, 'subscribers', 'token', 'TEXT') + ensureColumn(db, 'users', 'avatar', 'TEXT') } /** 若表中缺少某列则补上(用于老库升级) */ diff --git a/server/utils/upload.ts b/server/utils/upload.ts new file mode 100644 index 0000000..3e58a0f --- /dev/null +++ b/server/utils/upload.ts @@ -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 = { + '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: /),URL /uploads// + * - OSS 未配置 -> 存本地 /data/uploads//,URL 同上 + */ +export async function saveImage(data: Buffer, type: string, folder: string): Promise { + 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}` +}