From 5c3f3bca63b57ffa998cbd6cfd5000f8fcf6e166 Mon Sep 17 00:00:00 2001 From: chenchun Date: Thu, 6 Aug 2026 15:00:56 +0800 Subject: [PATCH 01/12] =?UTF-8?q?feat:=20=E5=85=A8=E9=87=8F=E8=90=BD?= =?UTF-8?q?=E5=9C=B0=E5=90=8E=E7=AB=AF=E4=B8=8E=E5=8A=9F=E8=83=BD=E9=97=AD?= =?UTF-8?q?=E7=8E=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 真实后端(server/):SQLite 存储 + scrypt 会话鉴权 + SMTP 邮件 - auth 注册/登录/登出/me/资料更新 - contact 联系表单(落库+邮件)、newsletter 订阅(去重) - favorites 作品收藏、comments 新闻评论、account 管理收件箱 - 用户系统 UI:个人中心 /account(资料/收藏/评论/管理员面板)、 收藏按钮、评论组件、登录/注册弹窗接真实 API(useApiError 错误映射) - 内容单点事实源:app/data/news|work 消除三处重复,页面全部引用 - 修复断链:首页动态/作品卡可点击、分享按钮真实动作、移除 # 死链、 语言切换器、社交链接统一 siteConfig - SEO:动态 sitemap/robots、JSON-LD、脚本生成真实 og-image.png - 列表增强:搜索 + 加载更多 - 部署自动化:build-and-push.sh 支持 git tag 版本化镜像; deploy.sh 一条命令构建推送+注入 Secret/ConfigMap+kubectl 滚动升级; deployment 挂 PVC 持久化;Dockerfile 支持 better-sqlite3 原生编译 - 组件注册去目录前缀,修复 AppLoader/AnimatedButton 等未渲染问题 --- .dockerignore | 7 +- .env.example | 29 + Dockerfile | 11 +- README.md | 122 ++-- app/app.vue | 26 +- app/components/common/CommentSection.vue | 154 +++++ app/components/common/FavoriteButton.vue | 71 +++ app/components/common/LoginModal.vue | 109 ++-- app/components/common/RegisterModal.vue | 156 +++-- app/components/home/HomePartnersWork.vue | 92 +-- app/components/home/HomeTechStack.vue | 2 +- app/components/home/HomeUpdates.vue | 95 +--- app/components/layouts/ArcticNewOneFooter.vue | 47 +- app/components/layouts/ArcticNewOneHeader.vue | 98 ++-- app/composables/useApiError.ts | 31 + app/config/site.ts | 27 + app/data/news.ts | 98 ++++ app/data/work.ts | 108 ++++ app/pages/account.vue | 308 ++++++++++ app/pages/contact.vue | 46 +- app/pages/news/[slug].vue | 175 +++--- app/pages/news/index.vue | 176 +++--- app/pages/work/[slug].vue | 164 +----- app/pages/work/index.vue | 156 ++--- app/stores/authModal.ts | 56 ++ app/stores/user.ts | 159 +++--- build-and-push.sh | 83 ++- deploy.sh | 108 ++++ deploy/README.md | 87 +-- deploy/deployment.yaml | 33 +- deploy/pvc.yaml | 19 + i18n/locales/en.json | 171 ++++-- i18n/locales/zh.json | 171 ++++-- nuxt.config.ts | 19 + package.json | 6 +- pnpm-lock.yaml | 535 +++++++++++------- pnpm-workspace.yaml | 1 + public/og-image.png | Bin 0 -> 82869 bytes public/robots.txt | 2 - scripts/generate-og.mjs | 139 +++++ server/api/account/admin.get.ts | 30 + server/api/account/comments.get.ts | 15 + server/api/auth/login.post.ts | 30 + server/api/auth/logout.post.ts | 14 + server/api/auth/me.get.ts | 13 + server/api/auth/me.patch.ts | 41 ++ server/api/auth/register.post.ts | 54 ++ server/api/comments.get.ts | 34 ++ server/api/comments.post.ts | 41 ++ server/api/contact.post.ts | 43 ++ server/api/favorites.delete.ts | 16 + server/api/favorites.get.ts | 13 + server/api/favorites.post.ts | 23 + server/api/newsletter.post.ts | 32 ++ server/routes/robots.txt.ts | 18 + server/routes/sitemap.xml.ts | 44 ++ server/utils/auth.ts | 134 +++++ server/utils/config.ts | 56 ++ server/utils/db.ts | 101 ++++ server/utils/email.ts | 52 ++ server/utils/validation.ts | 25 + 61 files changed, 3408 insertions(+), 1318 deletions(-) create mode 100644 .env.example create mode 100644 app/components/common/CommentSection.vue create mode 100644 app/components/common/FavoriteButton.vue create mode 100644 app/composables/useApiError.ts create mode 100644 app/config/site.ts create mode 100644 app/data/news.ts create mode 100644 app/data/work.ts create mode 100644 app/pages/account.vue create mode 100644 app/stores/authModal.ts create mode 100755 deploy.sh create mode 100644 deploy/pvc.yaml create mode 100644 public/og-image.png delete mode 100755 public/robots.txt create mode 100644 scripts/generate-og.mjs create mode 100644 server/api/account/admin.get.ts create mode 100644 server/api/account/comments.get.ts create mode 100644 server/api/auth/login.post.ts create mode 100644 server/api/auth/logout.post.ts create mode 100644 server/api/auth/me.get.ts create mode 100644 server/api/auth/me.patch.ts create mode 100644 server/api/auth/register.post.ts create mode 100644 server/api/comments.get.ts create mode 100644 server/api/comments.post.ts create mode 100644 server/api/contact.post.ts create mode 100644 server/api/favorites.delete.ts create mode 100644 server/api/favorites.get.ts create mode 100644 server/api/favorites.post.ts create mode 100644 server/api/newsletter.post.ts create mode 100644 server/routes/robots.txt.ts create mode 100644 server/routes/sitemap.xml.ts create mode 100644 server/utils/auth.ts create mode 100644 server/utils/config.ts create mode 100644 server/utils/db.ts create mode 100644 server/utils/email.ts create mode 100644 server/utils/validation.ts diff --git a/.dockerignore b/.dockerignore index d69511a..71a935c 100755 --- a/.dockerignore +++ b/.dockerignore @@ -1,10 +1,15 @@ # 依赖目录 node_modules/ -pnpm-workspace.yaml # 编译产出目录 .output/ .nuxt/ +.nitro/ +.cache/ +dist/ + +# 本地数据(开发数据库,不进镜像) +.data/ # 环境变量文件(通常不应该被打包进去) .env diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..a12906d --- /dev/null +++ b/.env.example @@ -0,0 +1,29 @@ +# ========================================================= +# Arcticnewone 本地开发环境变量示例 +# 复制为 .env 使用(.env 已被 gitignore,不会提交) +# +# Nuxt runtimeConfig 的环境变量映射约定:一律使用 NUXT_ 前缀 +# ========================================================= + +# 站点公开地址(用于 sitemap/robots/og 等绝对链接) +NUXT_PUBLIC_SITE_URL=https://personal.virtheart.com + +# 会话安全密钥(生产必须设置为高强度随机值) +# 生成方式: node -e "console.log(require('crypto').randomBytes(48).toString('hex'))" +NUXT_SESSION_SECRET=dev-change-me-to-a-long-random-string + +# 数据文件路径(默认:生产 /data/arcticnewone.db,开发 .data/arcticnewone.db) +# NUXT_DB_PATH=/data/arcticnewone.db + +# ---- SMTP 邮件(可选)---- +# 未配置时:联系表单与邮箱订阅仍会真实写入数据库,但不会发送邮件 +NUXT_SMTP_HOST= +NUXT_SMTP_PORT=587 +NUXT_SMTP_USER= +NUXT_SMTP_PASS= +NUXT_SMTP_FROM= +# 联系表单留言的接收邮箱 +NUXT_CONTACT_TO=chenchun@virtheart.com + +# 管理员邮箱(逗号分隔),命中邮箱的用户在个人中心显示管理面板 +NUXT_ADMIN_EMAILS=chenchun@virtheart.com diff --git a/Dockerfile b/Dockerfile index 60c86e4..637a88e 100755 --- a/Dockerfile +++ b/Dockerfile @@ -4,16 +4,19 @@ # 使用国内可访问的 DaoCloud 镜像源(Docker Hub 在国内不可达) FROM docker.m.daocloud.io/library/node:22-alpine AS builder -# 启用 corepack 并安装 pnpm -RUN corepack enable && corepack prepare pnpm@9 --activate +# 启用 corepack 并安装 pnpm(与本地 pnpm 11 保持一致,兼容 pnpm-workspace.yaml 配置) +RUN corepack enable && corepack prepare pnpm@11 --activate + +# 安装原生模块编译依赖(better-sqlite3 等,构建期兜底;产物无需运行期依赖) +RUN apk add --no-cache python3 make g++ # 设置工作目录 WORKDIR /app # 复制依赖相关文件 -COPY package.json pnpm-lock.yaml ./ +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ -# 安装依赖项 +# 安装依赖项(含原生模块编译;build 需要 devDependencies,故安装全部) RUN pnpm install --frozen-lockfile # 复制项目源代码 diff --git a/README.md b/README.md index 5104a48..15f8d4f 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,17 @@ # Arcticnewone 个人网站 -北极新一(Arcticnewone)的个人网站,提供个人介绍、作品集、工作室服务、动态资讯、工具箱与联系页面,是一个现代化的展示型站点。 +北极新一(Arcticnewone)的个人网站,提供个人介绍、作品集、工作室服务、动态资讯、工具箱与联系页面,是一个现代化的展示型站点。已内置**真实后端**(登录/注册、联系留言、邮箱订阅、作品收藏、新闻评论、管理员收件箱)与 **中英双语、SEO、搜索分页** 等完整功能。 ## 技术栈 -- [Nuxt 4](https://nuxt.com/) — 应用框架(服务端渲染 + 静态生成) +- [Nuxt 4](https://nuxt.com/) — 应用框架(服务端渲染 + Nitro 后端 API) - [Vue 3](https://vuejs.org/) — 视图层 - [Tailwind CSS](https://tailwindcss.com/) — 样式方案(通过 `@nuxtjs/tailwindcss` 集成) - [GSAP](https://gsap.com/) — 页面动画(配合 Lenis 平滑滚动) - [Pinia](https://pinia.vuejs.org/) — 状态管理 - [@nuxtjs/i18n](https://i18n.nuxtjs.org/) — 国际化(中/英双语) +- [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) — 数据存储(SQLite,K8s PVC 持久化) +- [nodemailer](https://nodemailer.com/) — 邮件发送(SMTP) - [@nuxt/icon](https://nuxt.com/modules/icon) — 图标 - [pnpm](https://pnpm.io/) — 包管理器 @@ -26,7 +28,10 @@ # 1. 安装依赖 pnpm install -# 2. 启动开发服务器(默认 http://localhost:3000) +# 2. 配置环境变量(可选,SMTP 未配置时联系/订阅仍会真实落库) +cp .env.example .env + +# 3. 启动开发服务器(默认 http://localhost:3000) pnpm dev ``` @@ -42,64 +47,101 @@ pnpm dev | `pnpm preview` | 本地预览生产构建 | | `pnpm start` | 以 Node 方式启动 `.output/server/index.mjs` | +## 功能一览 + +| 模块 | 说明 | +| --- | --- | +| 页面 | 首页、工作室、作品(列表/详情)、动态(列表/详情)、工具箱、联系、个人中心 | +| 用户系统 | 真实注册/登录/登出(scrypt 密码哈希 + httpOnly Cookie 会话) | +| 个人中心 | `/account`:资料编辑、作品收藏、我的评论;管理员可见联系/订阅收件箱 | +| 交互 | 作品收藏、新闻评论、分享(X/LinkedIn/复制链接)、搜索、加载更多 | +| 国际化 | 中/英双语,Header 一键切换(`no_prefix`,默认中文) | +| SEO | 动态 `sitemap.xml` / `robots.txt`、JSON-LD、自动生成的 `og-image.png` | +| 邮件 | SMTP 发送联系/订阅邮件;未配置 SMTP 时数据仍真实写入 SQLite | + +### 环境变量(详见 `.env.example`,Nuxt runtimeConfig 使用 `NUXT_` 前缀) + +| 变量 | 说明 | +| --- | --- | +| `NUXT_PUBLIC_SITE_URL` | 站点公开地址(sitemap/robots/og 绝对链接) | +| `NUXT_SESSION_SECRET` | 会话安全密钥(生产必须设置强随机值) | +| `NUXT_DB_PATH` | 数据库文件路径(默认生产 `/data/arcticnewone.db`,开发 `.data/`) | +| `NUXT_SMTP_HOST/PORT/USER/PASS/FROM` | SMTP 邮件服务(可选) | +| `NUXT_CONTACT_TO` | 联系表单留言收件邮箱 | +| `NUXT_ADMIN_EMAILS` | 管理员邮箱(逗号分隔),命中者个人中心可见管理面板 | + +> `deploy.sh` 中的对外变量名(`SESSION_SECRET`/`SMTP_*`/`CONTACT_TO`/`ADMIN_EMAILS`)会在写入 K8s Secret 时自动加 `NUXT_` 前缀。 + ## 项目结构 ```text . ├── app/ # 应用源码(Nuxt 4 约定目录) -│ ├── app.vue # 应用入口(全局 SEO / Meta) -│ ├── assets/ # 静态资源(样式、图片等) -│ ├── components/ # 组件(common / home) -│ ├── composables/ # 组合式函数 -│ ├── layouts/ # 布局 -│ ├── pages/ # 页面(首页、工作室、作品、动态、工具、联系) -│ ├── plugins/ # 插件(如 Lenis 平滑滚动) -│ ├── stores/ # Pinia 状态 -│ └── types/ # 类型定义 -├── i18n/ -│ └── locales/ # 国际化文案(zh.json / en.json) -├── public/ # 公开静态文件(favicon、robots.txt 等) -├── Dockerfile # 容器镜像构建 -├── deploy/ # 生产部署配置(Kubernetes Deployment/Service/Ingress) -├── docker-compose.yml # 本地容器编排(使用 SWR 镜像) -├── nuxt.config.ts # Nuxt 配置(模块、i18n、Tailwind 等) -├── tailwind.config.js # Tailwind 配置 -└── package.json # 项目依赖与脚本 +│ ├── app.vue # 应用入口(全局 SEO / Meta / JSON-LD) +│ ├── config/ # 站点配置(品牌、邮箱、社交链接) +│ ├── data/ # 内容单一事实源(news / work,列表/详情/首页共用) +│ ├── pages/ # 页面(含 account.vue 个人中心) +│ ├── components/ # 组件(common / home / layouts) +│ ├── stores/ # Pinia 状态(用户、认证弹窗) +│ └── ... +├── server/ # Nitro 后端(utils 数据/鉴权/邮件 + api 路由 + sitemap/robots) +├── i18n/locales/ # 国际化文案(zh.json / en.json) +├── scripts/ # 工具脚本(generate-og.mjs 生成分享图) +├── public/ # 公开静态文件 +├── deploy/ # 生产部署配置(K8s) +├── deploy.sh # 一条命令部署 / 升级 +├── build-and-push.sh # 版本化镜像构建推送(SWR) +└── Dockerfile ``` -## 构建与部署 +## 构建与部署(一条命令) -构建并推送镜像: +镜像版本取自 git tag(如 `0.0.1-dev` → `:0.0.1-dev`,同时更新 `:latest`),构建后推送华为云 SWR。 + +> SWR 兼容性:华为云 SWR 无法解析 Docker manifest list(多架构合并会报 `Invalid image`), +> 因此版本 tag 与 `latest` 以 **amd64 单架构 manifest** 输出(生产集群为 amd64); +> 同时分架构推送 `-amd64`/`-arm64` 标签,arm64 环境可按需使用。 ```bash -./build-and-push.sh +# 1. 打版本标签 +git add -A && git commit -m "release: 0.0.1-dev" +git tag 0.0.1-dev + +# 2. 设置环境变量(凭据绝不写入仓库) +export SWR_REGISTRY="swr.cn-north-4.myhuaweicloud.com" +export SWR_NAMESPACE="virtheart" +export SWR_USERNAME="<用户名>" +export SWR_PASSWORD="<密码>" +# 可选:export SESSION_SECRET="$(openssl rand -hex 32)" / SMTP_* / CONTACT_TO / ADMIN_EMAILS + +# 3. 一条命令:构建镜像 + 推送 + 更新集群 + 滚动升级 +./deploy.sh 0.0.1-dev # 不带参数则自动取最新 git tag ``` -脚本从环境变量读取 SWR 凭据(`SWR_REGISTRY`、`SWR_NAMESPACE`、`SWR_USERNAME`、`SWR_PASSWORD`), -多架构(`linux/amd64,linux/arm64`)构建并推送到华为云 SWR:分架构推送后用 `docker manifest` 合并为 `latest`(标准 Docker manifest list,SWR 可正常解析)。 +`deploy.sh` 自动完成:构建推送版本化镜像 → 注入 Secret(会话密钥/SMTP/管理员)与 ConfigMap(站点地址/DB 路径)→ `kubectl apply`(namespace/PVC/Deployment/Service/Ingress)→ 等待滚动更新 → 健康检查。 -Dockerfile 基础镜像使用国内可访问的 DaoCloud 镜像源(`docker.m.daocloud.io/library/node:22-alpine`,Docker Hub 在国内不可达)。 - -本地启动(使用 SWR 镜像,与生产一致): +### 仅构建镜像(不部署) ```bash -docker compose up -d +./build-and-push.sh # 版本取最新 git tag +./build-and-push.sh 0.0.1-dev # 显式指定版本 ``` -生产部署使用 `deploy/` 目录下的 Kubernetes 配置(Deployment / Service / Ingress), -镜像统一推送到华为云 SWR(`swr.cn-north-4.myhuaweicloud.com/virtheart/arcticnewone:latest`), -部署与回滚步骤见 [deploy/README.md](deploy/README.md)。 +### 生产部署说明 + +- 域名 `personal.virtheart.com`,Traefik Ingress + cert-manager 自动签发证书 +- SQLite 数据持久化在 PVC `arcticnewone-data`(挂载 `/data`),Pod 升级/重启不丢数据 +- 回滚:`kubectl rollout undo deployment/arcticnewone -n arcticnewone` +- 详见 [deploy/README.md](deploy/README.md) ## 国际化(i18n) -项目使用 `@nuxtjs/i18n` 实现中/英双语: - - 语言文件位于 `i18n/locales/`:`zh.json`(中文)、`en.json`(英文) -- 默认语言为中文(`defaultLocale: 'zh'`),URL 不包含语言前缀(`strategy: 'no_prefix'`),不自动探测浏览器语言 -- 组件中通过 `useI18n()` 的 `t()` 方法读取文案,例如 `t('nav.home')` - -新增文案时,在 `zh.json` 和 `en.json` 中同步添加对应键即可。 +- 默认语言为中文(`defaultLocale: 'zh'`),URL 不包含语言前缀(`strategy: 'no_prefix'`),Header 提供中/EN 切换 +- 组件中通过 `useI18n()` 的 `t()` 方法读取文案;新增文案时同步更新两个语言文件(可用根目录脚本校验键对齐) ## 说明 -本项目不含任何密钥或敏感信息;本地环境变量请使用 `.env` 文件(已被 `.gitignore` 忽略)。 +- 本项目不含任何密钥或敏感信息;本地环境变量请使用 `.env` 文件(已被 `.gitignore` 忽略) +- 联系/订阅依赖 SMTP:未配置时数据仍真实写入数据库,仅在管理面板可见但不会发邮件 +- 社交链接为品牌占位地址(`app/config/site.ts`),正式上线前请替换为真实账号 diff --git a/app/app.vue b/app/app.vue index 976880d..b68c4bf 100755 --- a/app/app.vue +++ b/app/app.vue @@ -1,18 +1,37 @@ diff --git a/app/components/common/FavoriteButton.vue b/app/components/common/FavoriteButton.vue new file mode 100644 index 0000000..e1c3d0f --- /dev/null +++ b/app/components/common/FavoriteButton.vue @@ -0,0 +1,71 @@ + + + diff --git a/app/components/common/LoginModal.vue b/app/components/common/LoginModal.vue index 8d87411..d83a5cc 100644 --- a/app/components/common/LoginModal.vue +++ b/app/components/common/LoginModal.vue @@ -2,7 +2,7 @@
@@ -35,7 +35,8 @@ v-model="account" type="text" required - :disabled="isLoggingIn" + autocomplete="username" + :disabled="isSubmitting" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed" :placeholder="t('auth.accountPlaceholder')" /> @@ -50,7 +51,8 @@ v-model="password" type="password" required - :disabled="isLoggingIn" + autocomplete="current-password" + :disabled="isSubmitting" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed" :placeholder="t('auth.passwordPlaceholder')" /> @@ -64,26 +66,21 @@ - -

- {{ t('auth.demoHint') }} -

- -

+

{{ t('auth.noAccount') }} -

@@ -98,86 +95,60 @@ import { ref, watch } from 'vue' import { useI18n } from 'vue-i18n' import { useUserStore } from '~/stores/user' +import { useAuthModalStore } from '~/stores/authModal' +import { useApiError } from '~/composables/useApiError' const { t } = useI18n() const userStore = useUserStore() +const authModal = useAuthModalStore() +const apiError = useApiError() -interface Props { - isOpen: boolean -} - -const props = defineProps() -const emit = defineEmits<{ - close: [] - switchToRegister: [] -}>() - -const modalRef = ref(null) const account = ref('') const password = ref('') -const isLoggingIn = ref(false) +const isSubmitting = ref(false) const errorMessage = ref('') -// 关闭模态框 const closeModal = () => { - if (!isLoggingIn.value) { - emit('close') + if (!isSubmitting.value) { + authModal.closeAll() } } -// 切换到注册 -const switchToRegister = () => { - emit('switchToRegister') -} - -// 处理登录 -const handleLogin = async () => { - if (isLoggingIn.value) return - - isLoggingIn.value = true - errorMessage.value = '' - - try { - const result = await userStore.login(account.value, password.value) - - if (result.success) { - // 登录成功,关闭模态框 +// 打开时重置表单 +watch( + () => authModal.isLoginOpen, + (open) => { + if (open) { account.value = '' password.value = '' - closeModal() - } else { - errorMessage.value = t('auth.loginError') + errorMessage.value = '' } - } catch (error) { - console.error('Login error:', error) - errorMessage.value = t('auth.loginError') - } finally { - isLoggingIn.value = false - } -} + }, +) -// 监听打开状态,重置表单 -watch(() => props.isOpen, (isOpen) => { - if (isOpen) { +const handleLogin = async () => { + if (isSubmitting.value) return + isSubmitting.value = true + errorMessage.value = '' + + const result = await userStore.login(account.value, password.value) + + if (result.success) { account.value = '' password.value = '' - errorMessage.value = '' - // 禁止背景滚动 - document.body.style.overflow = 'hidden' + authModal.closeAll() } else { - // 恢复滚动 - document.body.style.overflow = '' + errorMessage.value = apiError({ data: { code: result.code } }) } -}) + isSubmitting.value = false +} -// ESC 键关闭 +// ESC 关闭 const handleKeydown = (e: KeyboardEvent) => { - if (e.key === 'Escape' && props.isOpen) { + if (e.key === 'Escape' && authModal.isLoginOpen) { closeModal() } } - -// 添加键盘事件监听 if (typeof window !== 'undefined') { window.addEventListener('keydown', handleKeydown) } diff --git a/app/components/common/RegisterModal.vue b/app/components/common/RegisterModal.vue index cb600c5..c2c94fc 100644 --- a/app/components/common/RegisterModal.vue +++ b/app/components/common/RegisterModal.vue @@ -2,7 +2,7 @@
@@ -35,7 +35,8 @@ v-model="username" type="text" required - :disabled="isRegistering" + autocomplete="username" + :disabled="isSubmitting" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed" :placeholder="t('auth.usernamePlaceholder')" /> @@ -50,7 +51,8 @@ v-model="email" type="email" required - :disabled="isRegistering" + autocomplete="email" + :disabled="isSubmitting" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed" :placeholder="t('auth.emailPlaceholder')" /> @@ -64,7 +66,8 @@ id="reg-phone" v-model="phone" type="tel" - :disabled="isRegistering" + autocomplete="tel" + :disabled="isSubmitting" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed" :placeholder="t('auth.phonePlaceholder')" /> @@ -79,7 +82,8 @@ v-model="password" type="password" required - :disabled="isRegistering" + autocomplete="new-password" + :disabled="isSubmitting" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed" :placeholder="t('auth.passwordPlaceholder')" /> @@ -94,7 +98,8 @@ v-model="confirmPassword" type="password" required - :disabled="isRegistering" + autocomplete="new-password" + :disabled="isSubmitting" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed" :placeholder="t('auth.confirmPasswordPlaceholder')" /> @@ -113,21 +118,21 @@

{{ t('auth.alreadyHaveAccount') }} -

@@ -142,122 +147,89 @@ import { ref, watch } from 'vue' import { useI18n } from 'vue-i18n' import { useUserStore } from '~/stores/user' +import { useAuthModalStore } from '~/stores/authModal' +import { useApiError } from '~/composables/useApiError' const { t } = useI18n() const userStore = useUserStore() +const authModal = useAuthModalStore() +const apiError = useApiError() -interface Props { - isOpen: boolean -} - -const props = defineProps() -const emit = defineEmits<{ - close: [] - switchToLogin: [] -}>() - -const modalRef = ref(null) const username = ref('') const email = ref('') const phone = ref('') const password = ref('') const confirmPassword = ref('') -const isRegistering = ref(false) +const isSubmitting = ref(false) const errorMessage = ref('') const successMessage = ref('') -// 关闭模态框 const closeModal = () => { - if (!isRegistering.value) { - emit('close') + if (!isSubmitting.value) { + authModal.closeAll() } } -// 切换到登录 -const switchToLogin = () => { - emit('switchToLogin') -} - -// 处理注册 -const handleRegister = async () => { - if (isRegistering.value) return - - // 验证密码匹配 - if (password.value !== confirmPassword.value) { - errorMessage.value = t('auth.passwordMismatch') - return - } - - // 验证手机号格式(如果填写了) - if (phone.value && !/^1[3-9]\d{9}$/.test(phone.value)) { - errorMessage.value = t('auth.invalidPhone') - return - } - - isRegistering.value = true - errorMessage.value = '' - successMessage.value = '' - - try { - const result = await userStore.register({ - username: username.value, - email: email.value, - phone: phone.value, - password: password.value - }) - - if (result.success) { - // 注册成功 - successMessage.value = t('auth.registerSuccess') - - // 清空表单 +// 打开时重置表单 +watch( + () => authModal.isRegisterOpen, + (open) => { + if (open) { username.value = '' email.value = '' phone.value = '' password.value = '' confirmPassword.value = '' - - // 2秒后关闭并自动登录 - setTimeout(() => { - closeModal() - }, 2000) - } else { - errorMessage.value = result.error || t('auth.registerError') + errorMessage.value = '' + successMessage.value = '' } - } catch (error) { - console.error('Register error:', error) - errorMessage.value = t('auth.registerError') - } finally { - isRegistering.value = false - } -} + }, +) -// 监听打开状态,重置表单 -watch(() => props.isOpen, (isOpen) => { - if (isOpen) { +const handleRegister = async () => { + if (isSubmitting.value) return + errorMessage.value = '' + successMessage.value = '' + + if (password.value !== confirmPassword.value) { + errorMessage.value = t('auth.passwordMismatch') + return + } + if (phone.value && !/^1[3-9]\d{9}$/.test(phone.value)) { + errorMessage.value = t('auth.invalidPhone') + return + } + + isSubmitting.value = true + const result = await userStore.register({ + username: username.value, + email: email.value, + phone: phone.value, + password: password.value, + }) + + if (result.success) { + successMessage.value = t('auth.registerSuccess') username.value = '' email.value = '' phone.value = '' password.value = '' confirmPassword.value = '' - errorMessage.value = '' - successMessage.value = '' - // 禁止背景滚动 - document.body.style.overflow = 'hidden' + setTimeout(() => { + authModal.closeAll() + }, 1500) } else { - // 恢复滚动 - document.body.style.overflow = '' + errorMessage.value = apiError({ data: { code: result.code } }) } -}) + isSubmitting.value = false +} -// ESC 键关闭 +// ESC 关闭 const handleKeydown = (e: KeyboardEvent) => { - if (e.key === 'Escape' && props.isOpen) { + if (e.key === 'Escape' && authModal.isRegisterOpen) { closeModal() } } - -// 添加键盘事件监听 if (typeof window !== 'undefined') { window.addEventListener('keydown', handleKeydown) } diff --git a/app/components/home/HomePartnersWork.vue b/app/components/home/HomePartnersWork.vue index ed9d80b..bf14abe 100755 --- a/app/components/home/HomePartnersWork.vue +++ b/app/components/home/HomePartnersWork.vue @@ -3,6 +3,7 @@ import { onMounted, onUnmounted, ref, nextTick } from 'vue' import { useI18n } from 'vue-i18n' import gsap from 'gsap' import { ScrollTrigger } from 'gsap/ScrollTrigger' +import { workItems } from '~/data/work' gsap.registerPlugin(ScrollTrigger) @@ -49,46 +50,6 @@ const partners = [ }, ] -const toImageUrl = (prompt: string, imageSize: string) => { - const encoded = encodeURIComponent(prompt) - return `https://coresg-normal.trae.ai/api/ide/v1/text_to_image?prompt=${encoded}&image_size=${imageSize}` -} - -const workItems = [ - { - titleKey: 'home.work.items.forma', - year: '26', - image: toImageUrl( - 'high-end editorial product still life, minimal composition, matte ceramics and brushed aluminum on soft neutral background, studio lighting, shallow depth of field, premium, clean, realistic, 35mm photo', - 'landscape_16_9' - ), - }, - { - titleKey: 'home.work.items.oneStep', - year: '24', - image: toImageUrl( - 'architectural close-up, modern brutalist concrete facade with sharp shadows, minimal, cinematic lighting, high contrast, ultra realistic, 35mm photography, no people', - 'landscape_16_9' - ), - }, - { - titleKey: 'home.work.items.neroVision', - year: '25', - image: toImageUrl( - 'minimal graphic poster photographed in studio, black ink typography on off-white textured paper, premium editorial style, soft shadow, ultra realistic, no people', - 'landscape_16_9' - ), - }, - { - titleKey: 'home.work.items.boldMoves', - year: '24', - image: toImageUrl( - 'moody nighttime city street still life, neon reflection on wet asphalt, abstract bokeh, premium cinematic photography, no people, high detail', - 'landscape_16_9' - ), - }, -] as const - let ctx: gsap.Context | null = null const refresh = () => { @@ -140,12 +101,12 @@ onMounted(async () => { tl.to( next, { y: 0, duration: 1, ease: 'power2.out' }, - start + start, ) tl.to( prev, { scale: scaleTo, y: depthOffsetY, duration: 0.6, ease: 'power2.out' }, - start + 0.35 + start + 0.35, ) tl.set(prev, { scale: scaleTo, y: depthOffsetY }, start + 1) } @@ -235,29 +196,30 @@ onUnmounted(() => {
-
- -
-

- {{ t(item.titleKey) }} -

-

- {{ item.year }} © -

-
-
+ + +
+

+ {{ t(`work.items.${item.slug}.title`) }} +

+

+ {{ item.year }} © +

+
+
diff --git a/app/components/home/HomeTechStack.vue b/app/components/home/HomeTechStack.vue index 617eea6..a7738b0 100644 --- a/app/components/home/HomeTechStack.vue +++ b/app/components/home/HomeTechStack.vue @@ -15,7 +15,7 @@ v-for="(tech, index) in technologies" :key="tech.id" :ref="el => setTechRef(el, index)" - class="tech-tag absolute flex items-center gap-3 px-5 py-3 bg-white rounded-full shadow-lg border-2 cursor-pointer hover:scale-110 transition-transform duration-300" + class="tech-tag absolute flex items-center gap-3 px-5 py-3 bg-white rounded-full shadow-lg border-2 hover:scale-110 transition-transform duration-300" :class="tech.borderColor" :style="getTechStyle(index)" > diff --git a/app/components/home/HomeUpdates.vue b/app/components/home/HomeUpdates.vue index 5dfe25d..ed3b57b 100644 --- a/app/components/home/HomeUpdates.vue +++ b/app/components/home/HomeUpdates.vue @@ -13,11 +13,12 @@
-
- {{ t(`home.updates.categories.${item.category}`) }} + {{ t(`news.categories.${item.category}`) }}

- {{ t(`home.updates.items.${item.id}.title`) }} + {{ t(`news.items.${item.slug}.title`) }}

- {{ t(`home.updates.items.${item.id}.description`) }} + {{ t(`news.items.${item.slug}.excerpt`) }}

- {{ item.date }} + {{ formatNewsDate(item.date, locale) }}
-
+
@@ -73,10 +74,11 @@ import { ref, onMounted, onUnmounted, nextTick } from 'vue' import { useI18n } from 'vue-i18n' import gsap from 'gsap' import { ScrollTrigger } from 'gsap/ScrollTrigger' +import { newsItems, formatNewsDate } from '~/data/news' gsap.registerPlugin(ScrollTrigger) -const { t } = useI18n() +const { t, locale } = useI18n() const rootRef = ref(null) const headerRef = ref(null) @@ -87,62 +89,21 @@ const setCardRef = (el: any, index: number) => { if (el) cardElements.value[index] = el } -const updates = [ - { - id: 'project1', - category: 'project', - categoryIcon: 'ph:briefcase', - gradient: 'bg-gradient-to-br from-blue-500 via-purple-500 to-pink-500', - gridClass: 'col-span-12 md:col-span-6 md:row-span-2', - showDescription: true, - date: '2026-06-01' - }, - { - id: 'blog1', - category: 'blog', - categoryIcon: 'ph:article', - gradient: 'bg-gradient-to-br from-orange-500 to-red-500', - gridClass: 'col-span-12 md:col-span-3 md:row-span-1', - showDescription: false, - date: '2026-05-28' - }, - { - id: 'news1', - category: 'news', - categoryIcon: 'ph:newspaper', - gradient: 'bg-gradient-to-br from-green-500 to-emerald-500', - gridClass: 'col-span-12 md:col-span-3 md:row-span-1', - showDescription: false, - date: '2026-05-25' - }, - { - id: 'project2', - category: 'project', - categoryIcon: 'ph:briefcase', - gradient: 'bg-gradient-to-br from-indigo-500 to-blue-500', - gridClass: 'col-span-12 md:col-span-3 md:row-span-2', - showDescription: true, - date: '2026-05-20' - }, - { - id: 'blog2', - category: 'blog', - categoryIcon: 'ph:article', - gradient: 'bg-gradient-to-br from-pink-500 to-rose-500', - gridClass: 'col-span-12 md:col-span-6 md:row-span-1', - showDescription: false, - date: '2026-05-15' - }, - { - id: 'news2', - category: 'news', - categoryIcon: 'ph:newspaper', - gradient: 'bg-gradient-to-br from-amber-500 to-orange-500', - gridClass: 'col-span-12 md:col-span-3 md:row-span-1', - showDescription: false, - date: '2026-05-10' - } -] +// Bento 布局(与动态数据一一对应;分类图标/渐变/跨度) +const layout = [ + { categoryIcon: 'ph:article', gradient: 'bg-gradient-to-br from-blue-500 via-purple-500 to-pink-500', gridClass: 'col-span-12 md:col-span-6 md:row-span-2', showDescription: true }, + { categoryIcon: 'ph:briefcase', gradient: 'bg-gradient-to-br from-orange-500 to-red-500', gridClass: 'col-span-12 md:col-span-3 md:row-span-1', showDescription: false }, + { categoryIcon: 'ph:newspaper', gradient: 'bg-gradient-to-br from-green-500 to-emerald-500', gridClass: 'col-span-12 md:col-span-3 md:row-span-1', showDescription: false }, + { categoryIcon: 'ph:article', gradient: 'bg-gradient-to-br from-indigo-500 to-blue-500', gridClass: 'col-span-12 md:col-span-3 md:row-span-2', showDescription: true }, + { categoryIcon: 'ph:briefcase', gradient: 'bg-gradient-to-br from-pink-500 to-rose-500', gridClass: 'col-span-12 md:col-span-6 md:row-span-1', showDescription: false }, + { categoryIcon: 'ph:newspaper', gradient: 'bg-gradient-to-br from-amber-500 to-orange-500', gridClass: 'col-span-12 md:col-span-3 md:row-span-1', showDescription: false }, +] as const + +// 取前 6 条动态,绑定布局 +const updates = newsItems.slice(0, 6).map((item, i) => ({ + ...item, + ...layout[i], +})) // 卡片悬浮效果 const handleCardHover = (index: number, isHover: boolean) => { @@ -155,7 +116,7 @@ const handleCardHover = (index: number, isHover: boolean) => { ? '0 25px 50px -12px rgba(0, 0, 0, 0.25)' : '0 10px 15px -3px rgba(0, 0, 0, 0.1)', duration: 0.3, - ease: 'power2.out' + ease: 'power2.out', }) } @@ -171,7 +132,7 @@ onMounted(async () => { gsap.set(card, { autoAlpha: 0, y: 60, scale: 0.9 }) }) - // 入场动画(无 pin):标题 + 卡片错开出现 + // 入场动画:标题 + 卡片错开出现 const tl = gsap.timeline() tl.to(headerRef.value, { autoAlpha: 1, y: 0, duration: 0.8, ease: 'power3.out' }, 0) diff --git a/app/components/layouts/ArcticNewOneFooter.vue b/app/components/layouts/ArcticNewOneFooter.vue index 8a096b5..914c202 100755 --- a/app/components/layouts/ArcticNewOneFooter.vue +++ b/app/components/layouts/ArcticNewOneFooter.vue @@ -5,6 +5,7 @@ import { gsap } from 'gsap' import { ScrollTrigger } from 'gsap/ScrollTrigger' import FooterLogo from '~/components/common/FooterLogo.vue' import AnimatedButton from '~/components/common/AnimatedButton.vue' +import { siteConfig } from '~/config/site' gsap.registerPlugin(ScrollTrigger) @@ -43,14 +44,8 @@ const handleNewsletterSubmit = async () => { subscribeStatus.value = 'idle' try { - // 模拟 API 调用 - 你需要替换为真实的 Newsletter 服务 - // 可选方案: - // 1. Mailchimp: await $fetch('/api/newsletter/subscribe', { method: 'POST', body: { email: newsletterEmail.value } }) - // 2. ConvertKit, SendGrid, 或其他邮件服务 - - await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟网络延迟 - - console.log('Newsletter subscription:', newsletterEmail.value) + // 真实订阅:落库 + 尽力发送欢迎邮件 + await $fetch('/api/newsletter', { method: 'POST', body: { email: newsletterEmail.value } }) subscribeStatus.value = 'success' newsletterEmail.value = '' @@ -61,8 +56,12 @@ const handleNewsletterSubmit = async () => { }, 3000) } catch (error) { - console.error('Newsletter subscription error:', error) - subscribeStatus.value = 'error' + // 已在订阅列表视为成功(用户确实已订阅) + if ((error as any)?.data?.code === 'ALREADY_SUBSCRIBED') { + subscribeStatus.value = 'success' + } else { + subscribeStatus.value = 'error' + } setTimeout(() => { subscribeStatus.value = 'idle' @@ -227,10 +226,10 @@ onUnmounted(() => {
diff --git a/app/components/layouts/ArcticNewOneHeader.vue b/app/components/layouts/ArcticNewOneHeader.vue index a6484cf..20bfd85 100755 --- a/app/components/layouts/ArcticNewOneHeader.vue +++ b/app/components/layouts/ArcticNewOneHeader.vue @@ -6,16 +6,18 @@ import gsap from 'gsap' import { ScrollTrigger } from 'gsap/ScrollTrigger' import { useAppStore } from '~/stores/app' import { useUserStore } from '~/stores/user' +import { useAuthModalStore } from '~/stores/authModal' import AppLogo from '~/components/common/AppLogo.vue' import LoginModal from '~/components/common/LoginModal.vue' import RegisterModal from '~/components/common/RegisterModal.vue' gsap.registerPlugin(ScrollTrigger) -const { t } = useI18n() +const { t, locale, setLocale } = useI18n() const route = useRoute() const appStore = useAppStore() const userStore = useUserStore() +const authModal = useAuthModalStore() // 恢复用户状态 onMounted(() => { @@ -36,46 +38,15 @@ const topHeaderRef = ref(null) const bottomHeaderRef = ref(null) const mobileMenuRef = ref(null) const isMobileMenuOpen = ref(false) -const isLoginModalOpen = ref(false) -const isRegisterModalOpen = ref(false) const isUserMenuOpen = ref(false) let topHeaderTween: gsap.core.Tween | null = null let bottomHeaderScrollTrigger: ReturnType | null = null let isBottomHeaderVisible = false let fallbackTimer: ReturnType | null = null -// 打开登录弹窗 -const openLoginModal = () => { - isLoginModalOpen.value = true - isRegisterModalOpen.value = false -} - -// 关闭登录弹窗 -const closeLoginModal = () => { - isLoginModalOpen.value = false -} - -// 打开注册弹窗 -const openRegisterModal = () => { - isRegisterModalOpen.value = true - isLoginModalOpen.value = false -} - -// 关闭注册弹窗 -const closeRegisterModal = () => { - isRegisterModalOpen.value = false -} - -// 从登录切换到注册 -const switchToRegister = () => { - isLoginModalOpen.value = false - isRegisterModalOpen.value = true -} - -// 从注册切换到登录 -const switchToLogin = () => { - isRegisterModalOpen.value = false - isLoginModalOpen.value = true +// 语言切换 +const switchLocale = () => { + setLocale(locale.value === 'zh' ? 'en' : 'zh') } // 切换用户菜单 @@ -368,12 +339,21 @@ if (typeof window !== 'undefined') { - + - - + + - - + +
diff --git a/app/composables/useApiError.ts b/app/composables/useApiError.ts new file mode 100644 index 0000000..465f332 --- /dev/null +++ b/app/composables/useApiError.ts @@ -0,0 +1,31 @@ +import { useI18n } from 'vue-i18n' + +/** + * 把后端 API 错误码映射为已翻译的 i18n 文案。 + * 用法:`const apiError = useApiError()`;`apiError(err)` 返回中文/英文消息。 + */ +export function useApiError() { + const { t } = useI18n() + + const codeKeyMap: Record = { + USERNAME_TAKEN: 'auth.usernameTaken', + EMAIL_TAKEN: 'auth.emailTaken', + INVALID_CREDENTIALS: 'auth.invalidCredentials', + UNAUTHORIZED: 'auth.loginRequired', + FORBIDDEN: 'auth.loginRequired', + ALREADY_SUBSCRIBED: 'newsletter.alreadySubscribed', + VALIDATION_ERROR: 'auth.serverError', + } + + return (err: any, fallbackKey = 'auth.serverError'): string => { + const code = err?.data?.code + if (code && codeKeyMap[code]) { + return t(codeKeyMap[code]) + } + // 后端若带具体 message 也如实展示 + if (typeof err?.data?.message === 'string' && err.data.message) { + return err.data.message + } + return t(fallbackKey) + } +} diff --git a/app/config/site.ts b/app/config/site.ts new file mode 100644 index 0000000..0eb3903 --- /dev/null +++ b/app/config/site.ts @@ -0,0 +1,27 @@ +/** + * 站点全局元数据(品牌、联系、社交)。 + * + * 单一事实源:Footer、联系页、账号页等不再各自硬编码邮箱/社交链接。 + * + * 注意:社交地址为品牌官方占位链接,正式上线前请替换为北极新一真实账号。 + */ +export interface SocialLink { + name: string + icon: string + url: string +} + +export const siteConfig = { + brand: 'ArcticNewOne', + brandZh: '北极新一', + email: 'chenchun@virtheart.com', + infoEmail: 'info@virtheart.com', + wechat: 'LucskyNew', + copyright: '© 2026 北极新一工作室', + socials: [ + { name: 'X', icon: 'ph:x-logo', url: 'https://x.com/arcticnewone' }, + { name: 'Instagram', icon: 'ph:instagram-logo', url: 'https://instagram.com/arcticnewone' }, + { name: 'LinkedIn', icon: 'ph:linkedin-logo', url: 'https://www.linkedin.com/company/arcticnewone' }, + { name: 'GitHub', icon: 'ph:github-logo', url: 'https://github.com/arcticnewone' }, + ], +} diff --git a/app/data/news.ts b/app/data/news.ts new file mode 100644 index 0000000..89a612b --- /dev/null +++ b/app/data/news.ts @@ -0,0 +1,98 @@ +/** + * 动态(news)单一事实源。 + * + * 列表页、详情页、首页 HomeUpdates 一律引用本模块,杜绝三处重复。 + * 标题/摘要/正文属于本地化文案,按 slug 存放在 i18n(news.items..*), + * 本模块只保存与语言无关的结构化元数据。 + */ +export interface NewsItem { + slug: string + category: 'insights' | 'projects' | 'announcements' + /** 分类徽章 tailwind 类(静态字符串,Tailwind 扫描 ./app/** 可命中) */ + badge: string + date: string + readTime: string + author: string + image: string +} + +export const newsItems: NewsItem[] = [ + { + slug: 'design-trends-2026', + category: 'insights', + badge: 'bg-purple-100 text-purple-700', + date: '2026-05-28', + readTime: '5', + author: 'ArcticNewOne', + image: 'https://picsum.photos/id/1/800/500', + }, + { + slug: 'forma-digital-launch', + category: 'projects', + badge: 'bg-blue-100 text-blue-700', + date: '2026-05-15', + readTime: '3', + author: 'ArcticNewOne', + image: 'https://picsum.photos/id/201/800/500', + }, + { + slug: 'studio-expansion', + category: 'announcements', + badge: 'bg-green-100 text-green-700', + date: '2026-05-10', + readTime: '2', + author: 'ArcticNewOne', + image: 'https://picsum.photos/id/164/800/500', + }, + { + slug: 'ux-research-methods', + category: 'insights', + badge: 'bg-purple-100 text-purple-700', + date: '2026-04-28', + readTime: '7', + author: 'ArcticNewOne', + image: 'https://picsum.photos/id/180/800/500', + }, + { + slug: 'bold-moves-case-study', + category: 'projects', + badge: 'bg-blue-100 text-blue-700', + date: '2026-04-20', + readTime: '6', + author: 'ArcticNewOne', + image: 'https://picsum.photos/id/119/800/500', + }, + { + slug: 'new-tools-integration', + category: 'announcements', + badge: 'bg-green-100 text-green-700', + date: '2026-04-12', + readTime: '4', + author: 'ArcticNewOne', + image: 'https://picsum.photos/id/326/800/500', + }, +] + +export const newsBySlug: Record = Object.fromEntries( + newsItems.map((item) => [item.slug, item]), +) + +export function getNewsCategories(): Array { + return ['insights', 'projects', 'announcements'] +} + +/** 显示用的日期(本地化格式化在组件内完成) */ +export function formatNewsDate(date: string, locale: string): string { + const d = new Date(`${date}T00:00:00`) + if (Number.isNaN(d.getTime())) return date + return new Intl.DateTimeFormat(locale === 'zh' ? 'zh-CN' : 'en-US', { + year: 'numeric', + month: 'long', + day: 'numeric', + }).format(d) +} + +/** 显示用的阅读时长(本地化文案在 i18n,数字在此) */ +export function newsReadTime(item: NewsItem): string { + return item.readTime +} diff --git a/app/data/work.ts b/app/data/work.ts new file mode 100644 index 0000000..5220b16 --- /dev/null +++ b/app/data/work.ts @@ -0,0 +1,108 @@ +/** + * 作品(work)单一事实源。 + * + * 列表页、详情页、首页 HomePartnersWork 一律引用本模块,杜绝三处重复。 + * 标题/概述属于本地化文案,按 slug 存放在 i18n(work.items..*)。 + * + * 说明:`url` 只在存在真实线上地址时填写;没有真实地址的作品 + * 详情页不渲染「访问项目」按钮,避免 `#` 死链。 + */ +export interface WorkItem { + slug: string + category: 'webDesign' | 'branding' | 'development' + year: string + tags: string[] + image: string + gallery: string[] + /** 真实线上地址;不存在时省略,详情页隐藏「访问项目」按钮 */ + url?: string +} + +export const workItems: WorkItem[] = [ + { + slug: 'forma-digital', + category: 'webDesign', + year: '2026', + tags: ['Web Design', 'E-commerce', 'React'], + image: 'https://picsum.photos/id/201/1200/800', + gallery: [ + 'https://picsum.photos/id/201/800/600', + 'https://picsum.photos/id/202/800/600', + 'https://picsum.photos/id/203/800/600', + 'https://picsum.photos/id/204/800/600', + ], + }, + { + slug: 'one-step', + category: 'branding', + year: '2024', + tags: ['Branding', 'Marketing', 'UI/UX'], + image: 'https://picsum.photos/id/180/1200/800', + gallery: [ + 'https://picsum.photos/id/180/800/600', + 'https://picsum.photos/id/181/800/600', + 'https://picsum.photos/id/182/800/600', + 'https://picsum.photos/id/183/800/600', + ], + }, + { + slug: 'nero-vision', + category: 'development', + year: '2025', + tags: ['Development', 'Vue.js', 'Node.js'], + image: 'https://picsum.photos/id/119/1200/800', + gallery: [ + 'https://picsum.photos/id/119/800/600', + 'https://picsum.photos/id/120/800/600', + 'https://picsum.photos/id/121/800/600', + 'https://picsum.photos/id/122/800/600', + ], + }, + { + slug: 'bold-moves', + category: 'webDesign', + year: '2024', + tags: ['Web Design', '3D', 'Three.js'], + image: 'https://picsum.photos/id/164/1200/800', + gallery: [ + 'https://picsum.photos/id/164/800/600', + 'https://picsum.photos/id/165/800/600', + 'https://picsum.photos/id/166/800/600', + 'https://picsum.photos/id/167/800/600', + ], + }, + { + slug: 'echo-labs', + category: 'branding', + year: '2025', + tags: ['Branding', 'Visual Identity', 'Corporate'], + image: 'https://picsum.photos/id/101/1200/800', + gallery: [ + 'https://picsum.photos/id/101/800/600', + 'https://picsum.photos/id/102/800/600', + 'https://picsum.photos/id/103/800/600', + 'https://picsum.photos/id/104/800/600', + ], + }, + { + slug: 'flux-api', + category: 'development', + year: '2025', + tags: ['Development', 'API', 'Python'], + image: 'https://picsum.photos/id/326/1200/800', + gallery: [ + 'https://picsum.photos/id/326/800/600', + 'https://picsum.photos/id/327/800/600', + 'https://picsum.photos/id/328/800/600', + 'https://picsum.photos/id/329/800/600', + ], + }, +] + +export const workBySlug: Record = Object.fromEntries( + workItems.map((item) => [item.slug, item]), +) + +export function getWorkCategories(): Array { + return ['webDesign', 'branding', 'development'] +} diff --git a/app/pages/account.vue b/app/pages/account.vue new file mode 100644 index 0000000..7ea4556 --- /dev/null +++ b/app/pages/account.vue @@ -0,0 +1,308 @@ + + + diff --git a/app/pages/contact.vue b/app/pages/contact.vue index 0f6b230..54ec377 100755 --- a/app/pages/contact.vue +++ b/app/pages/contact.vue @@ -139,7 +139,7 @@ @@ -198,6 +198,7 @@ import { useI18n } from 'vue-i18n' import { useSeoMeta } from '#imports' import gsap from 'gsap' import { useAppStore } from '~/stores/app' +import { siteConfig } from '~/config/site' const { t } = useI18n() const appStore = useAppStore() @@ -234,16 +235,8 @@ const handleSubmit = async () => { statusMessage.value = '' try { - // 模拟 API 调用 - 你需要替换为真实的邮件服务 - // 可选方案: - // 1. 使用 Nuxt server API: await $fetch('/api/contact', { method: 'POST', body: form }) - // 2. 使用 Formspree: await fetch('https://formspree.io/f/YOUR_ID', { ... }) - // 3. 使用 EmailJS 等第三方服务 - - await new Promise(resolve => setTimeout(resolve, 1500)) // 模拟网络延迟 - - // 模拟成功 - console.log('Form submitted:', form) + // 真实提交到后端(落库 + 尽力发送邮件) + await $fetch('/api/contact', { method: 'POST', body: { ...form } }) submitStatus.value = 'success' statusMessage.value = t('contact.form.successMessage') || 'Message sent successfully! We will get back to you soon.' @@ -253,16 +246,17 @@ const handleSubmit = async () => { form[key as keyof typeof form] = '' }) - // 3秒后重置状态 + // 4秒后重置状态 setTimeout(() => { submitStatus.value = 'idle' statusMessage.value = '' - }, 3000) + }, 4000) } catch (error) { console.error('Form submission error:', error) submitStatus.value = 'error' - statusMessage.value = t('contact.form.errorMessage') || 'Failed to send message. Please try again or contact us directly.' + // 如实展示后端错误 + statusMessage.value = (error as any)?.data?.message || t('contact.form.errorMessage') || 'Failed to send message. Please try again or contact us directly.' } finally { isSubmitting.value = false } @@ -362,28 +356,8 @@ interface SocialLink { url: string } -const socials: SocialLink[] = [ - { - name: 'Twitter', - icon: 'ph:x-logo', - url: 'https://twitter.com' - }, - { - name: 'Instagram', - icon: 'ph:instagram-logo', - url: 'https://instagram.com' - }, - { - name: 'LinkedIn', - icon: 'ph:linkedin-logo', - url: 'https://linkedin.com' - }, - { - name: 'GitHub', - icon: 'ph:github-logo', - url: 'https://github.com' - } -] +// 社交链接统一取自站点配置(单一事实源) +const socials: SocialLink[] = siteConfig.socials diff --git a/app/components/admin/AdminImageUpload.vue b/app/components/admin/AdminImageUpload.vue new file mode 100644 index 0000000..7864f6b --- /dev/null +++ b/app/components/admin/AdminImageUpload.vue @@ -0,0 +1,86 @@ + + + diff --git a/app/components/admin/AdminSidebar.vue b/app/components/admin/AdminSidebar.vue new file mode 100644 index 0000000..6f54702 --- /dev/null +++ b/app/components/admin/AdminSidebar.vue @@ -0,0 +1,68 @@ + + + diff --git a/app/components/home/HomePartnersWork.vue b/app/components/home/HomePartnersWork.vue index bf14abe..62b7e34 100755 --- a/app/components/home/HomePartnersWork.vue +++ b/app/components/home/HomePartnersWork.vue @@ -1,13 +1,26 @@ + + + + diff --git a/app/middleware/admin.ts b/app/middleware/admin.ts new file mode 100644 index 0000000..db48bae --- /dev/null +++ b/app/middleware/admin.ts @@ -0,0 +1,23 @@ +import { defineNuxtRouteMiddleware, navigateTo } from '#app' +import { useUserStore } from '~/stores/user' +import { useAuthModalStore } from '~/stores/authModal' + +/** + * 后台路由守卫(/admin/**):仅管理员可访问。 + * - SSR 不拦截(真实防护在 admin API 的 requireAdmin); + * - 客户端依据已恢复的会话判定,未登录则弹出登录框并回退,非管理员回首页。 + */ +export default defineNuxtRouteMiddleware(() => { + if (import.meta.server) return + + const userStore = useUserStore() + + if (!userStore.isAuthenticated) { + const authModal = useAuthModalStore() + authModal.openLogin() + return navigateTo('/account') + } + if (userStore.user?.role !== 'admin') { + return navigateTo('/') + } +}) diff --git a/app/pages/account.vue b/app/pages/account.vue index 7ea4556..6047f15 100644 --- a/app/pages/account.vue +++ b/app/pages/account.vue @@ -26,6 +26,17 @@

{{ userStore.user?.email }}

+ +
+ + + {{ t('account.adminEntry') }} + +
+
- - -
-
-

{{ t('account.admin.contacts') }}

-

{{ t('account.admin.emptyContacts') }}

-
-
-
-
- {{ c.name }} - {{ c.email }} -
- - {{ c.delivered ? t('account.admin.delivered') : t('account.admin.notDelivered') }} - -
-

{{ c.subject }}

-

{{ c.message }}

-

{{ formatDate(c.createdAt) }}

-
-
-
- -
-

{{ t('account.admin.subscribers') }}

-

{{ t('account.admin.emptySubscribers') }}

-
-
- {{ s.email }} - {{ formatDate(s.createdAt) }} -
-
-
-
@@ -169,7 +145,6 @@ import { useSeoMeta } from '#imports' import gsap from 'gsap' import { useUserStore } from '~/stores/user' import { useAuthModalStore } from '~/stores/authModal' -import { workBySlug } from '~/data/work' import { useApiError } from '~/composables/useApiError' const { t, locale } = useI18n() @@ -187,9 +162,6 @@ const tabs = computed(() => { { key: 'favorites', label: t('account.favorites') }, { key: 'comments', label: t('account.comments') }, ] - if (userStore.user?.role === 'admin') { - list.push({ key: 'admin', label: t('account.adminTitle') }) - } return list }) @@ -198,7 +170,6 @@ const switchTab = (key: string) => { activeTab.value = key if (key === 'favorites') loadFavorites() if (key === 'comments') loadComments() - if (key === 'admin') loadAdmin() } const formatDate = (raw?: string) => { @@ -241,11 +212,18 @@ const saveProfile = async () => { } // ---- 收藏 ---- -const favorites = ref([]) +interface FavedWork { slug: string; titleZh: string; titleEn: string; image: string | null } +const favorites = ref([]) +const favTitle = (w: FavedWork) => (locale.value === 'zh' ? w.titleZh : w.titleEn) + const loadFavorites = async () => { try { - const data = await $fetch<{ slugs: string[] }>('/api/favorites') - favorites.value = data.slugs + const [favRes, workRes] = await Promise.all([ + $fetch<{ slugs: string[] }>('/api/favorites'), + $fetch<{ works: FavedWork[] }>('/api/work'), + ]) + const bySlug = new Map(workRes.works.map((w) => [w.slug, w])) + favorites.value = favRes.slugs.map((s) => bySlug.get(s)).filter(Boolean) as FavedWork[] } catch (err) { console.error('load favorites error:', err) } @@ -253,7 +231,7 @@ const loadFavorites = async () => { const removeFavorite = async (slug: string) => { try { await $fetch('/api/favorites', { method: 'DELETE', body: { workSlug: slug } }) - favorites.value = favorites.value.filter((s) => s !== slug) + favorites.value = favorites.value.filter((f) => f.slug !== slug) } catch (err) { console.error('remove favorite error:', err) } @@ -270,22 +248,6 @@ const loadComments = async () => { } } -// ---- 管理面板 ---- -const adminData = reactive<{ - contacts: Array<{ id: number; name: string; email: string; subject: string; message: string; delivered: number; createdAt: string }> - subscribers: Array<{ id: number; email: string; createdAt: string }> -}>({ contacts: [], subscribers: [] }) - -const loadAdmin = async () => { - try { - const data = await $fetch('/api/account/admin') - adminData.contacts = data.contacts - adminData.subscribers = data.subscribers - } catch (err) { - console.error('load admin error:', err) - } -} - // ---- 页面进场动画 ---- const mainRef = ref(null) let ctx: gsap.Context | null = null diff --git a/app/pages/admin/comments.vue b/app/pages/admin/comments.vue new file mode 100644 index 0000000..76d8ab8 --- /dev/null +++ b/app/pages/admin/comments.vue @@ -0,0 +1,208 @@ + + + diff --git a/app/pages/admin/contacts.vue b/app/pages/admin/contacts.vue new file mode 100644 index 0000000..5c9eeef --- /dev/null +++ b/app/pages/admin/contacts.vue @@ -0,0 +1,175 @@ + + + diff --git a/app/pages/admin/index.vue b/app/pages/admin/index.vue new file mode 100644 index 0000000..13e65fc --- /dev/null +++ b/app/pages/admin/index.vue @@ -0,0 +1,135 @@ + + + diff --git a/app/pages/admin/news.vue b/app/pages/admin/news.vue new file mode 100644 index 0000000..e612e8f --- /dev/null +++ b/app/pages/admin/news.vue @@ -0,0 +1,533 @@ + + + diff --git a/app/pages/admin/subscribers.vue b/app/pages/admin/subscribers.vue new file mode 100644 index 0000000..1b406e7 --- /dev/null +++ b/app/pages/admin/subscribers.vue @@ -0,0 +1,171 @@ + + + diff --git a/app/pages/admin/users.vue b/app/pages/admin/users.vue new file mode 100644 index 0000000..d6fa44f --- /dev/null +++ b/app/pages/admin/users.vue @@ -0,0 +1,212 @@ + + + diff --git a/app/pages/admin/work.vue b/app/pages/admin/work.vue new file mode 100644 index 0000000..d96b27a --- /dev/null +++ b/app/pages/admin/work.vue @@ -0,0 +1,709 @@ + + + diff --git a/app/pages/news/[slug].vue b/app/pages/news/[slug].vue index ecc3dd4..f976a14 100644 --- a/app/pages/news/[slug].vue +++ b/app/pages/news/[slug].vue @@ -14,7 +14,7 @@
@@ -23,7 +23,7 @@
{{ t(`news.categories.${article.category}`) }} @@ -48,41 +48,38 @@
- +
-

- {{ t(`news.detail.items.${slug}.content`) }} -

+
@@ -135,12 +132,12 @@ class="group block rounded-2xl overflow-hidden bg-white shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1" >
- +
{{ formatNewsDate(related.date, locale) }}

- {{ t(`news.items.${related.slug}.title`) }} + {{ locText(related.titleZh, related.titleEn) }}

@@ -155,25 +152,76 @@ import { computed, ref } from 'vue' import { useRoute } from 'vue-router' import { useI18n } from 'vue-i18n' import { useSeoMeta, createError } from '#imports' -import { newsBySlug, newsItems, formatNewsDate } from '~/data/news' const { t, locale } = useI18n() const route = useRoute() const slug = route.params.slug as string -const article = newsBySlug[slug] +interface Block { + type: 'paragraph' | 'heading' | 'quote' | 'image' + text: string +} -if (!article) { +interface ArticleItem { + slug: string + category: 'insights' | 'projects' | 'announcements' + titleZh: string + titleEn: string + excerptZh: string + excerptEn: string + contentZh: Block[] + contentEn: Block[] + image: string | null + date: string | null + readTime: number + author: string +} + +const [{ data, error }, { data: listData }] = await Promise.all([ + useFetch<{ article: ArticleItem }>(`/api/news/${slug}`), + useFetch<{ articles: ArticleItem[] }>('/api/news'), +]) + +// 未发布 / 不存在 → 404 +if (error.value || !data.value?.article) { throw createError({ statusCode: 404, statusMessage: 'Article not found' }) } -const title = computed(() => t(`news.items.${slug}.title`)) +const article = computed(() => data.value!.article) -const relatedArticles = newsItems.filter((a) => a.slug !== slug).slice(0, 3) +const locText = (zh: string, en: string) => (locale.value === 'zh' ? zh : en) + +function formatNewsDate(date: string | null, loc: string): string { + if (!date) return '' + const d = new Date(`${date}T00:00:00`) + if (Number.isNaN(d.getTime())) return date + return new Intl.DateTimeFormat(loc === 'zh' ? 'zh-CN' : 'en-US', { + year: 'numeric', + month: 'long', + day: 'numeric', + }).format(d) +} + +const categoryBadge: Record = { + insights: 'bg-purple-100 text-purple-700', + projects: 'bg-blue-100 text-blue-700', + announcements: 'bg-green-100 text-green-700', +} + +const title = computed(() => locText(article.value.titleZh, article.value.titleEn)) + +// 正文内容块(按当前语言选择 contentZh / contentEn) +const blocks = computed(() => + locale.value === 'zh' ? article.value.contentZh : article.value.contentEn, +) + +const relatedArticles = computed(() => + (listData.value?.articles ?? []).filter((a) => a.slug !== slug).slice(0, 3), +) useSeoMeta({ title: () => `${title.value} - ${t('news.title')}`, - description: () => t(`news.items.${slug}.excerpt`), + description: () => locText(article.value.excerptZh, article.value.excerptEn), }) // ---- 分享(真实动作) ---- diff --git a/app/pages/news/index.vue b/app/pages/news/index.vue index 5f827bc..468b416 100644 --- a/app/pages/news/index.vue +++ b/app/pages/news/index.vue @@ -58,15 +58,15 @@ >
{{ t(`news.categories.${article.category}`) }} @@ -86,11 +86,11 @@

- {{ t(`news.items.${article.slug}.title`) }} + {{ locText(article.titleZh, article.titleEn) }}

- {{ t(`news.items.${article.slug}.excerpt`) }} + {{ locText(article.excerptZh, article.excerptEn) }}

@@ -127,11 +127,48 @@ import { useI18n } from 'vue-i18n' import { useSeoMeta } from '#imports' import gsap from 'gsap' import { useAppStore } from '~/stores/app' -import { newsItems, formatNewsDate, getNewsCategories } from '~/data/news' const { t, locale } = useI18n() const appStore = useAppStore() +interface ArticleItem { + slug: string + category: 'insights' | 'projects' | 'announcements' + titleZh: string + titleEn: string + excerptZh: string + excerptEn: string + image: string | null + date: string | null + readTime: number + author: string +} + +// 内容 API(仅已发布,date 降序) +const { data } = await useFetch<{ articles: ArticleItem[] }>('/api/news') +const articles = computed(() => data.value?.articles ?? []) + +// 双语选择:切换语言即时生效(内容双字段已在 API 返回,无需重新请求) +const locText = (zh: string, en: string) => (locale.value === 'zh' ? zh : en) + +function formatNewsDate(date: string | null, loc: string): string { + if (!date) return '' + const d = new Date(`${date}T00:00:00`) + if (Number.isNaN(d.getTime())) return date + return new Intl.DateTimeFormat(loc === 'zh' ? 'zh-CN' : 'en-US', { + year: 'numeric', + month: 'long', + day: 'numeric', + }).format(d) +} + +// 分类徽章样式(insights=紫、projects=蓝、announcements=绿) +const categoryBadge: Record = { + insights: 'bg-purple-100 text-purple-700', + projects: 'bg-blue-100 text-blue-700', + announcements: 'bg-green-100 text-green-700', +} + const headerWrapRef = ref(null) const titleRef = ref(null) const descRef = ref(null) @@ -144,16 +181,16 @@ const visibleCount = ref(0) const PAGE_SIZE = 6 -const categories = ['all', ...getNewsCategories()] +const categories = ['all', 'insights', 'projects', 'announcements'] // 分类 + 搜索过滤(标题/摘要按当前语言文案匹配) const filteredNews = computed(() => { const kw = keyword.value.trim().toLowerCase() - return newsItems.filter((item) => { + return articles.value.filter((item) => { if (activeCategory.value !== 'all' && item.category !== activeCategory.value) return false if (!kw) return true - const title = t(`news.items.${item.slug}.title`).toLowerCase() - const excerpt = t(`news.items.${item.slug}.excerpt`).toLowerCase() + const title = locText(item.titleZh, item.titleEn).toLowerCase() + const excerpt = locText(item.excerptZh, item.excerptEn).toLowerCase() return title.includes(kw) || excerpt.includes(kw) }) }) diff --git a/app/pages/work/[slug].vue b/app/pages/work/[slug].vue index 32a141a..f4c8925 100644 --- a/app/pages/work/[slug].vue +++ b/app/pages/work/[slug].vue @@ -14,7 +14,7 @@
@@ -34,7 +34,7 @@ {{ title }}

- {{ t(`work.items.${slug}.description`) }} + {{ description }}

@@ -48,26 +48,26 @@

{{ t('work.detail.overview') }}

- {{ t(`work.detail.items.${slug}.overview`) }} + {{ locText(project.overviewZh, project.overviewEn) }}

{{ t('work.detail.challenge') }}

- {{ t(`work.detail.items.${slug}.challenge`) }} + {{ locText(project.challengeZh, project.challengeEn) }}

{{ t('work.detail.solution') }}

- {{ t(`work.detail.items.${slug}.solution`) }} + {{ locText(project.solutionZh, project.solutionEn) }}

-
+

{{ t('work.detail.gallery') }}

{{ t('work.detail.client') }}

-

{{ t(`work.detail.items.${slug}.client`) }}

+

{{ locText(project.clientZh, project.clientEn) }}

{{ t('work.detail.year') }}

@@ -97,7 +97,7 @@

{{ t('work.detail.duration') }}

-

{{ t(`work.detail.items.${slug}.duration`) }}

+

{{ locText(project.durationZh, project.durationEn) }}

{{ t('work.detail.services') }}

@@ -146,11 +146,11 @@ class="group block rounded-2xl overflow-hidden bg-white shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1" >
- +
-

{{ t(`work.items.${related.slug}.title`) }}

-

{{ related.tags[0] }}

+

{{ locText(related.titleZh, related.titleEn) }}

+

{{ related.tags?.[0] }}

@@ -164,24 +164,58 @@ import { computed } from 'vue' import { useRoute } from 'vue-router' import { useI18n } from 'vue-i18n' import { useSeoMeta, createError } from '#imports' -import { workBySlug, workItems } from '~/data/work' -const { t } = useI18n() +const { t, locale } = useI18n() const route = useRoute() const slug = route.params.slug as string -const project = workBySlug[slug] +interface WorkItem { + slug: string + category: 'webDesign' | 'branding' | 'development' + titleZh: string + titleEn: string + descriptionZh: string + descriptionEn: string + overviewZh: string + overviewEn: string + challengeZh: string + challengeEn: string + solutionZh: string + solutionEn: string + clientZh: string + clientEn: string + durationZh: string + durationEn: string + year: string + tags: string[] + image: string | null + gallery: string[] + url: string | null +} -if (!project) { +const [{ data, error }, { data: listData }] = await Promise.all([ + useFetch<{ work: WorkItem }>(`/api/work/${slug}`), + useFetch<{ works: WorkItem[] }>('/api/work'), +]) + +// 未发布 / 不存在 → 404 +if (error.value || !data.value?.work) { throw createError({ statusCode: 404, statusMessage: 'Project not found' }) } -const title = computed(() => t(`work.items.${slug}.title`)) +const project = computed(() => data.value!.work) -const relatedProjects = workItems.filter((p) => p.slug !== slug).slice(0, 3) +const locText = (zh: string, en: string) => (locale.value === 'zh' ? zh : en) + +const title = computed(() => locText(project.value.titleZh, project.value.titleEn)) +const description = computed(() => locText(project.value.descriptionZh, project.value.descriptionEn)) + +const relatedProjects = computed(() => + (listData.value?.works ?? []).filter((p) => p.slug !== slug).slice(0, 3), +) useSeoMeta({ title: () => `${title.value} - ${t('work.title')}`, - description: () => t(`work.items.${slug}.description`), + description: () => description.value, }) diff --git a/app/pages/work/index.vue b/app/pages/work/index.vue index d1e0b18..f9e7f03 100644 --- a/app/pages/work/index.vue +++ b/app/pages/work/index.vue @@ -58,8 +58,8 @@ >
@@ -69,13 +69,13 @@

- {{ t(`work.items.${project.slug}.title`) }} + {{ locText(project.titleZh, project.titleEn) }}

-

{{ t(`work.items.${project.slug}.description`) }}

+

{{ locText(project.descriptionZh, project.descriptionEn) }}

('/api/work') +const works = computed(() => data.value?.works ?? []) + +// 双语选择:切换语言即时生效 +const locText = (zh: string, en: string) => (locale.value === 'zh' ? zh : en) + const headerWrapRef = ref(null) const titleRef = ref(null) const descRef = ref(null) @@ -128,16 +146,16 @@ const visibleCount = ref(0) const PAGE_SIZE = 4 -const categories = ['all', ...getWorkCategories()] +const categories = ['all', 'webDesign', 'branding', 'development'] // 分类 + 搜索过滤(标题/描述按当前语言文案匹配) const filteredWork = computed(() => { const kw = keyword.value.trim().toLowerCase() - return workItems.filter((item) => { + return works.value.filter((item) => { if (activeCategory.value !== 'all' && item.category !== activeCategory.value) return false if (!kw) return true - const title = t(`work.items.${item.slug}.title`).toLowerCase() - const desc = t(`work.items.${item.slug}.description`).toLowerCase() + const title = locText(item.titleZh, item.titleEn).toLowerCase() + const desc = locText(item.descriptionZh, item.descriptionEn).toLowerCase() return title.includes(kw) || desc.includes(kw) }) }) diff --git a/app/plugins/auth.client.ts b/app/plugins/auth.client.ts new file mode 100644 index 0000000..624a8e3 --- /dev/null +++ b/app/plugins/auth.client.ts @@ -0,0 +1,10 @@ +import { defineNuxtPlugin } from '#app' + +/** + * 客户端启动时从服务端会话恢复登录状态(在路由守卫前完成, + * 保证 admin 中间件与 /account 页能立即拿到真实用户)。 + */ +export default defineNuxtPlugin(async () => { + const userStore = useUserStore() + await userStore.restoreUser() +}) diff --git a/deploy.sh b/deploy.sh index 7d6a3fe..e4bfd47 100755 --- a/deploy.sh +++ b/deploy.sh @@ -17,6 +17,7 @@ # SMTP_HOST/PORT/USER/PASS/FROM 邮件 # CONTACT_TO 联系表单收件邮箱 # ADMIN_EMAILS 管理员邮箱(逗号分隔) +# ADMIN_INITIAL_PASSWORD 预置管理员初始密码(缺省自动生成并打印) # SITE_URL 站点公开地址(默认 https://personal.virtheart.com) # ========================================================= set -euo pipefail @@ -72,6 +73,13 @@ if [ -z "${SESSION_SECRET}" ]; then fi # 注意:Nuxt runtimeConfig 的环境变量一律使用 NUXT_ 前缀 +# 预置管理员密码(首次部署生成,用于 DB 初始化时创建 admin 账号) +ADMIN_INITIAL_PASSWORD="${ADMIN_INITIAL_PASSWORD:-}" +if [ -z "${ADMIN_INITIAL_PASSWORD}" ]; then + ADMIN_INITIAL_PASSWORD="$(openssl rand -base64 18 2>/dev/null | tr -d '/+=' | cut -c1-16)" + echo " (已自动生成预置管理员密码,请保存: ${ADMIN_INITIAL_PASSWORD})" +fi + kubectl create secret generic app-secrets -n "${NAMESPACE}" \ --from-literal="NUXT_SESSION_SECRET=${SESSION_SECRET}" \ --from-literal="NUXT_SMTP_HOST=${SMTP_HOST:-}" \ @@ -81,6 +89,7 @@ kubectl create secret generic app-secrets -n "${NAMESPACE}" \ --from-literal="NUXT_SMTP_FROM=${SMTP_FROM:-}" \ --from-literal="NUXT_CONTACT_TO=${CONTACT_TO:-}" \ --from-literal="NUXT_ADMIN_EMAILS=${ADMIN_EMAILS:-}" \ + --from-literal="NUXT_ADMIN_INITIAL_PASSWORD=${ADMIN_INITIAL_PASSWORD}" \ --dry-run=client -o yaml | kubectl apply -f - >/dev/null kubectl create configmap app-config -n "${NAMESPACE}" \ diff --git a/i18n/locales/en.json b/i18n/locales/en.json index af074b1..935978b 100755 --- a/i18n/locales/en.json +++ b/i18n/locales/en.json @@ -277,32 +277,6 @@ }, "cta": "View Project", "backToList": "Back to Work", - "items": { - "forma-digital": { - "title": "Forma Digital", - "description": "A modern e-commerce platform with seamless user experience and dynamic product showcases." - }, - "one-step": { - "title": "One Step", - "description": "Brand identity and marketing campaign for a fitness app focused on sustainable habits." - }, - "nero-vision": { - "title": "Nero Vision", - "description": "Full-stack web application for creative professionals to manage their portfolios." - }, - "bold-moves": { - "title": "Bold Moves", - "description": "Interactive website showcasing innovative architectural designs with 3D visualizations." - }, - "echo-labs": { - "title": "Echo Labs", - "description": "Corporate branding and visual identity for a tech startup in the AI space." - }, - "flux-api": { - "title": "Flux API", - "description": "Scalable REST API with comprehensive documentation and developer tools." - } - }, "detail": { "overview": "Overview", "challenge": "Challenge", @@ -314,51 +288,7 @@ "duration": "Duration", "services": "Services", "visitProject": "Visit Project", - "relatedProjects": "Related Projects", - "items": { - "forma-digital": { - "overview": "Forma Digital is a modern e-commerce platform designed to provide a seamless shopping experience. We redesigned the entire user interface with a minimalist design approach, focusing on product showcase and conversion optimization.", - "challenge": "The client needed a platform that could both showcase premium products and deliver a smooth shopping experience. The existing website was slow, had poor mobile experience, and low conversion rates.", - "solution": "We built the platform with React + Next.js, implementing server-side rendering and static generation for blazing fast load times. The product pages feature immersive large-format imagery with smooth animation transitions.", - "client": "Forma Digital Inc.", - "duration": "3 months" - }, - "one-step": { - "overview": "One Step is a fitness app focused on building healthy habits. We created a complete brand visual identity system including logo design, UI interface, and marketing materials.", - "challenge": "In the competitive fitness app market, how to stand out through brand design and establish unique brand recognition.", - "solution": "With the core concept of 'one step at a time', we designed a clean and powerful brand identity. Using gradient colors and rounded graphic language to convey health, positivity, and progress.", - "client": "One Step Fitness", - "duration": "2 months" - }, - "nero-vision": { - "overview": "Nero Vision is a portfolio management platform for creative professionals, helping designers and artists showcase and manage their work.", - "challenge": "Creative professionals need a platform that can perfectly showcase work while being easy to manage. Existing solutions are either too complex or have poor display quality.", - "solution": "We developed a full-stack application with Vue.js + Node.js, designing an intuitive drag-and-drop portfolio management interface with beautiful display templates.", - "client": "Nero Studio", - "duration": "4 months" - }, - "bold-moves": { - "overview": "Bold Moves is an interactive website showcasing innovative architectural designs through 3D visualization technology, letting users experience architecture immersively.", - "challenge": "How to present complex architectural designs in an intuitive and engaging way to general users while maintaining professionalism.", - "solution": "We used Three.js for high-quality 3D rendering with smooth interactive design, allowing users to appreciate architectural details from any angle, with lighting effects and material displays.", - "client": "Bold Moves Architecture", - "duration": "5 months" - }, - "echo-labs": { - "overview": "Echo Labs is an AI tech startup. We created a complete brand visual identity system and corporate website for them.", - "challenge": "AI brands need to convey both technology and humanity, avoiding being too cold or technical.", - "solution": "With the concept of 'echo', we designed a dynamic brand identity. Using dark themes with gradient colors for a tech feel, while rounded graphic language adds approachability.", - "client": "Echo Labs AI", - "duration": "3 months" - }, - "flux-api": { - "overview": "Flux API is a scalable REST API service platform with comprehensive documentation and developer tools to help developers integrate quickly.", - "challenge": "API documentation and developer experience are core competitive advantages. How to make complex APIs easy to understand and use.", - "solution": "We designed interactive API documentation with online testing and code generation. Multi-language SDKs and detailed tutorials significantly reduce the learning curve for developers.", - "client": "Flux Technologies", - "duration": "6 months" - } - } + "relatedProjects": "Related Projects" } }, "studio": { @@ -419,97 +349,9 @@ "announcements": "Announcements" }, "minutes": "min", - "items": { - "design-trends-2026": { - "title": "Design Trends Shaping 2026", - "excerpt": "Explore the emerging design trends defining digital experiences this year, from minimalism to bold typography." - }, - "forma-digital-launch": { - "title": "Forma Digital Platform Launch", - "excerpt": "We are excited to announce the successful launch of Forma Digital, a revolutionary e-commerce experience." - }, - "studio-expansion": { - "title": "Studio Expansion Announcement", - "excerpt": "ArcticNewOne is growing! We are expanding our team and capabilities to serve you better." - }, - "ux-research-methods": { - "title": "Modern UX Research Methods", - "excerpt": "Dive into the latest user experience research methodologies, from remote testing to behavioral analytics." - }, - "bold-moves-case-study": { - "title": "Bold Moves: A Case Study", - "excerpt": "Behind the scenes of our award-winning architectural visualization project featuring cutting-edge 3D technology." - }, - "new-tools-integration": { - "title": "New Tools Added to Our Platform", - "excerpt": "Check out the latest additions to our toolbox across design, development and collaboration." - } - }, "detail": { "shareArticle": "Share Article", - "relatedArticles": "Related Articles", - "items": { - "design-trends-2026": { - "content": "In 2026, the design industry is undergoing a profound transformation. From the return of minimalism to the rise of bold typography, from the普及 of 3D elements to the maturity of AI-assisted design, these trends are redefining the boundaries of digital experiences.", - "section1Title": "The Return of Minimalism", - "section1Content": "In an age of information overload, users increasingly渴望 clean, clear interfaces. 2026's minimalism isn't just 'less is more' — it's about delivering more value in limited space through careful information architecture and visual hierarchy.", - "quote": "Good design isn't about adding more, it's about removing the unnecessary. In 2026, this matters more than ever.", - "section2Title": "Bold Typography & Dynamic Text", - "section2Content": "Typography is moving from supporting actor to leading role. Large, high-contrast font designs are becoming important brand expression tools. Dynamic text effects are making typography a living, interactive element rather than static decoration.", - "section3Title": "Maturity of AI-Assisted Design", - "section3Content": "AI tools are shifting from 'replacing designers' to 'empowering designers.' Smart layout suggestions, automated color schemes, and real-time design feedback let designers focus on creativity and strategy rather than repetitive execution." - }, - "forma-digital-launch": { - "content": "After three months of careful crafting, we're excited to announce the official launch of the Forma Digital e-commerce platform! This project is one of our team's most challenging works to date.", - "section1Title": "Project Background", - "section1Content": "Forma Digital is an e-commerce brand focusing on premium home goods. They needed a platform that could perfectly showcase product quality while delivering a smooth shopping experience.", - "quote": "The ArcticNewOne team not only understood our needs but exceeded our expectations. After the new platform launched, our conversion rate increased by 45%.", - "section2Title": "Technical Highlights", - "section2Content": "We used React + Next.js for server-side rendering and static generation. Through lazy loading, code splitting, and CDN acceleration, we reduced first load time from 4.5s to 1.2s.", - "section3Title": "Results", - "section3Content": "After launch, user停留 time increased by 60%, bounce rate decreased by 35%, and conversion rate improved by 45%." - }, - "studio-expansion": { - "content": "With continued business growth and increasing client demand, we're excited to announce the official expansion of ArcticNewOne Studio!", - "section1Title": "Team Growth", - "section1Content": "We're adding 5 senior designers and 3 senior developers covering frontend, backend, UI/UX, and more. All new members have extensive industry experience.", - "quote": "Talent is our most valuable asset. By expanding our team, we can take on more projects while maintaining consistent high-quality delivery.", - "section2Title": "Service Upgrade", - "section2Content": "In addition to existing services, we're adding data visualization, AI application development, AR/VR experience design, and other cutting-edge services.", - "section3Title": "Looking Ahead", - "section3Content": "We plan to complete 50+ projects and serve 30+ new clients in the coming year while continuing to explore new possibilities." - }, - "ux-research-methods": { - "content": "UX research is the foundation of design decisions. In 2026, as technology evolves and user behaviors change, UX research methods continue to advance.", - "section1Title": "Remote User Testing", - "section1Content": "Remote user testing has become mainstream. Through professional platforms, we can recruit test users globally and gather broader feedback in less time.", - "quote": "Remote testing not only reduces costs but more importantly lets us access more authentic user scenarios.", - "section2Title": "Behavioral Data Analysis", - "section2Content": "Through heatmaps, scroll depth, click streams, and other behavioral data, we can objectively understand how users interact with products.", - "section3Title": "AI-Assisted Analysis", - "section3Content": "AI tools help us analyze user feedback more efficiently. Sentiment analysis, topic clustering, and trend prediction help extract valuable insights from massive data." - }, - "bold-moves-case-study": { - "content": "Bold Moves is an interactive website showcasing innovative architectural designs. This article provides an in-depth look at the design思路, technical implementation, and final results.", - "section1Title": "Design Philosophy", - "section1Content": "Bold Moves wanted to showcase architectural beauty digitally. We decided to use 3D visualization to let users appreciate architectural details from any angle.", - "quote": "We didn't just want a showcase website — we wanted a digital space where users could 'walk into' the architecture.", - "section2Title": "Technical Challenges", - "section2Content": "High-quality 3D rendering requires significant computing power, but web performance is limited. We achieved smooth interactions through model optimization, LOD techniques, and WebGL rendering.", - "section3Title": "Final Results", - "section3Content": "The project received widespread acclaim and won multiple design awards. Average user停留 time exceeded 5 minutes, well above industry average." - }, - "new-tools-integration": { - "content": "To better serve our clients, we continuously expand and improve our toolbox. Recently, we've added several practical tools covering design, development, collaboration, and more.", - "section1Title": "Design Tool Upgrades", - "section1Content": "We've引入 the latest design collaboration platform supporting real-time multi-person editing, version management, and design system integration.", - "quote": "Good tools significantly boost team efficiency. The right toolchain is key to delivering quality work.", - "section2Title": "Development Tool Enhancements", - "section2Content": "Added automated testing frameworks, performance monitoring tools, and code quality checks to help identify and resolve issues during development.", - "section3Title": "Collaboration Tool Optimization", - "section3Content": "We upgraded our project management platform with new Kanban views, time tracking, and resource allocation features for better project oversight." - } - } + "relatedArticles": "Related Articles" } }, "auth": { @@ -584,7 +426,8 @@ "date": "Date", "delivered": "Delivered to inbox", "notDelivered": "Not delivered (SMTP not configured)" - } + }, + "adminEntry": "Admin Panel" }, "comments": { "title": "Comments", diff --git a/i18n/locales/zh.json b/i18n/locales/zh.json index 5e01efb..bf61d45 100755 --- a/i18n/locales/zh.json +++ b/i18n/locales/zh.json @@ -277,32 +277,6 @@ }, "cta": "查看项目", "backToList": "返回作品列表", - "items": { - "forma-digital": { - "title": "Forma Digital", - "description": "现代化的电商平台,无缝用户体验与动态产品展示。" - }, - "one-step": { - "title": "One Step", - "description": "为健身应用打造的品牌形象与营销战役,聚焦可持续习惯养成。" - }, - "nero-vision": { - "title": "Nero Vision", - "description": "面向创意专业人士的全栈作品集管理应用。" - }, - "bold-moves": { - "title": "Bold Moves", - "description": "以 3D 可视化展示创新建筑设计的交互式网站。" - }, - "echo-labs": { - "title": "Echo Labs", - "description": "AI 科技创业公司的企业品牌与视觉识别。" - }, - "flux-api": { - "title": "Flux API", - "description": "具备完善文档与开发者工具的可扩展 REST API 服务。" - } - }, "detail": { "overview": "项目概述", "challenge": "项目挑战", @@ -314,51 +288,7 @@ "duration": "周期", "services": "服务内容", "visitProject": "访问项目", - "relatedProjects": "相关项目", - "items": { - "forma-digital": { - "overview": "Forma Digital 是一个现代化的电商平台,致力于为用户提供无缝的购物体验。我们重新设计了整个用户界面,采用极简主义设计风格,突出产品展示,提升转化率。", - "challenge": "客户需要一个既能展示高端产品,又能提供流畅购物体验的平台。原有的网站加载缓慢,用户体验差,转化率低下。", - "solution": "我们采用了 React + Next.js 技术栈,实现了服务端渲染和静态生成,大幅提升加载速度。同时重新设计了产品展示页面,采用沉浸式大图展示,配合流畅的动画过渡。", - "client": "Forma Digital Inc.", - "duration": "3 个月" - }, - "one-step": { - "overview": "One Step 是一款专注于健康习惯养成的健身应用。我们为其打造了完整的品牌视觉识别系统,包括 Logo 设计、UI 界面和营销物料。", - "challenge": "在竞争激烈的健身应用市场中,如何通过品牌设计脱颖而出,建立独特的品牌认知。", - "solution": "我们以「一步一个脚印」为核心理念,设计了简洁有力的品牌标识。采用渐变色彩和圆润的图形语言,传达健康、积极、向上的品牌调性。", - "client": "One Step Fitness", - "duration": "2 个月" - }, - "nero-vision": { - "overview": "Nero Vision 是一个面向创意专业人士的作品集管理平台,帮助设计师和艺术家展示和管理他们的创作。", - "challenge": "创意人士需要一个既能完美展示作品,又能方便管理的平台。现有解决方案要么太复杂,要么展示效果不佳。", - "solution": "我们采用 Vue.js + Node.js 全栈开发,设计了直观的拖拽式作品管理界面,配合精美的展示模板,让创意人士轻松打造个人品牌。", - "client": "Nero Studio", - "duration": "4 个月" - }, - "bold-moves": { - "overview": "Bold Moves 是一个展示创新建筑设计的交互式网站,通过 3D 可视化技术,让用户身临其境地体验建筑之美。", - "challenge": "如何将复杂的建筑设计以直观、吸引人的方式展示给普通用户,同时保持专业性。", - "solution": "我们使用 Three.js 实现了高质量的 3D 渲染,配合流畅的交互设计,用户可以从任意角度欣赏建筑细节。同时加入了光影效果和材质展示,提升视觉冲击力。", - "client": "Bold Moves Architecture", - "duration": "5 个月" - }, - "echo-labs": { - "overview": "Echo Labs 是一家 AI 领域的科技创业公司,我们为其打造了完整的品牌视觉识别系统和企业官网。", - "challenge": "AI 领域的品牌需要既体现科技感,又要有人文温度,避免过于冷冰冰的技术感。", - "solution": "我们以「回声」为概念,设计了富有动感的品牌标识。采用深色主题配合渐变色彩,营造科技感的同时,通过圆润的图形语言增添亲和力。", - "client": "Echo Labs AI", - "duration": "3 个月" - }, - "flux-api": { - "overview": "Flux API 是一个可扩展的 REST API 服务平台,提供全面的文档和开发者工具,帮助开发者快速集成。", - "challenge": "API 文档和开发者体验是技术产品的核心竞争力,如何让复杂的 API 变得易于理解和使用。", - "solution": "我们设计了交互式 API 文档,支持在线测试和代码生成。同时提供了多语言 SDK 和详细的教程,大幅降低开发者的学习成本。", - "client": "Flux Technologies", - "duration": "6 个月" - } - } + "relatedProjects": "相关项目" } }, "studio": { @@ -419,97 +349,9 @@ "announcements": "公告通知" }, "minutes": "分钟", - "items": { - "design-trends-2026": { - "title": "2026 年设计趋势展望", - "excerpt": "从极简主义的回归到大胆排版的兴起,从 3D 元素普及到 AI 辅助设计成熟,探索塑造今年数字体验的前沿趋势。" - }, - "forma-digital-launch": { - "title": "Forma Digital 电商平台正式上线", - "excerpt": "我们很高兴地宣布 Forma Digital 电商平台正式上线,上线后转化率提升 45%。" - }, - "studio-expansion": { - "title": "工作室扩张公告", - "excerpt": "ArcticNewOne 正在成长!我们正在扩展团队与服务能力,以更好地服务客户。" - }, - "ux-research-methods": { - "title": "现代 UX 研究方法", - "excerpt": "深入解析影响我们设计决策的最新用户体验研究方法,从远程测试到行为数据分析。" - }, - "bold-moves-case-study": { - "title": "Bold Moves:项目复盘", - "excerpt": "走进我们屡获殊荣的建筑可视化项目幕后,见证前沿 3D 技术如何重塑用户体验。" - }, - "new-tools-integration": { - "title": "工具箱新增多款实用工具", - "excerpt": "看看我们工具箱的最新成员,覆盖设计、开发、协作,助你精简工作流、提升生产力。" - } - }, "detail": { "shareArticle": "分享文章", - "relatedArticles": "相关文章", - "items": { - "design-trends-2026": { - "content": "2026 年,设计行业正在经历一场深刻的变革。从极简主义的回归到大胆排版的兴起,从 3D 元素的普及到 AI 辅助设计的成熟,这些趋势正在重新定义数字体验的边界。作为设计从业者,我们需要紧跟这些变化,才能为客户创造更具竞争力的作品。", - "section1Title": "极简主义的回归", - "section1Content": "在信息过载的时代,用户越来越渴望简洁、清晰的界面。2026 年的极简主义不再是简单的「少即是多」,而是通过精心的信息架构和视觉层次,在有限的空间内传达更多价值。留白不再是空白,而是一种有意为之的设计语言。", - "quote": "好的设计不是添加更多,而是去除不必要的。在 2026 年,这一点比以往任何时候都更加重要。", - "section2Title": "大胆排版与动态文字", - "section2Content": "排版正在从配角变成主角。大尺寸、高对比度的字体设计正在成为品牌表达的重要手段。动态文字效果的普及,让排版不再是静态的装饰,而是能够与用户互动的活元素。", - "section3Title": "AI 辅助设计的成熟", - "section3Content": "AI 工具正在从「替代设计师」转向「增强设计师」。智能布局建议、自动化配色方案、实时设计反馈等功能,让设计师能够专注于创意和策略,而非重复性的执行工作。" - }, - "forma-digital-launch": { - "content": "经过三个月的精心打造,我们很高兴地宣布 Forma Digital 电商平台正式上线!这个项目是我们团队迄今为止最具挑战性的作品之一,也是我们技术实力和设计能力的集中体现。", - "section1Title": "项目背景", - "section1Content": "Forma Digital 是一家专注于高端家居用品的电商品牌。他们需要一个能够完美展示产品质感、提供流畅购物体验的平台。原有的网站存在加载缓慢、移动端体验差、转化率低等问题。", - "quote": "北极新一团队不仅理解我们的需求,更超越了我们的期望。新平台上线后,我们的转化率提升了 45%。", - "section2Title": "技术亮点", - "section2Content": "我们采用了 React + Next.js 技术栈,实现了服务端渲染和静态生成。通过图片懒加载、代码分割、CDN 加速等技术手段,将首屏加载时间从 4.5 秒降低到 1.2 秒。", - "section3Title": "成果展示", - "section3Content": "新平台上线后,用户停留时间增加了 60%,跳出率降低了 35%,转化率提升了 45%。客户对新平台的设计和性能都非常满意。" - }, - "studio-expansion": { - "content": "随着业务的持续增长和客户需求的不断增加,我们很高兴地宣布 ArcticNewOne 工作室正式扩展!我们将增加新的团队成员,拓展服务能力,为客户提供更优质的数字化解决方案。", - "section1Title": "团队扩展", - "section1Content": "我们将新增 5 名资深设计师和 3 名高级开发工程师,覆盖前端、后端、UI/UX 等多个领域。这些新成员都拥有丰富的行业经验,曾服务于多家知名企业。", - "quote": "人才是我们最宝贵的资产。通过扩展团队,我们能够承接更多项目,同时保持一贯的高品质交付。", - "section2Title": "服务升级", - "section2Content": "除了现有的网页设计、品牌设计、程序开发等服务,我们还将新增数据可视化、AI 应用开发、AR/VR 体验设计等前沿服务。", - "section3Title": "展望未来", - "section3Content": "我们计划在未来一年内完成 50+ 项目,服务 30+ 新客户。同时,我们将继续深耕技术创新,探索更多可能性,为客户创造更大价值。" - }, - "ux-research-methods": { - "content": "用户体验研究是设计决策的基础。在 2026 年,随着技术的发展和用户行为的变化,UX 研究方法也在不断演进。本文将介绍几种最有效的现代 UX 研究方法。", - "section1Title": "远程用户测试", - "section1Content": "远程用户测试已经成为 UX 研究的主流方法。通过专业的远程测试平台,我们可以在短时间内招募到全球各地的测试用户,获取更广泛的反馈。", - "quote": "远程测试不仅降低了成本,更重要的是让我们能够接触到更真实的用户场景。", - "section2Title": "行为数据分析", - "section2Content": "通过热力图、滚动深度、点击流等行为数据,我们可以客观地了解用户如何与产品互动。这些数据弥补了传统访谈和问卷的不足,提供了更真实的用户行为洞察。", - "section3Title": "AI 辅助分析", - "section3Content": "AI 工具正在帮助我们更高效地分析用户反馈。情感分析、主题聚类、趋势预测等功能,让我们能够从海量数据中快速提取有价值的洞察。" - }, - "bold-moves-case-study": { - "content": "Bold Moves 是一个展示创新建筑设计的交互式网站项目。本文将深入介绍这个项目的设计思路、技术实现和最终成果。", - "section1Title": "设计理念", - "section1Content": "Bold Moves 希望通过数字方式展示建筑设计的魅力。我们决定采用 3D 可视化技术,让用户能够从任意角度欣赏建筑细节,获得沉浸式的体验。", - "quote": "我们想要的不只是一个展示网站,而是一个能够让用户「走进」建筑的数字空间。", - "section2Title": "技术挑战", - "section2Content": "高质量的 3D 渲染需要强大的计算能力,而网页端的性能有限。我们通过模型优化、LOD 技术、WebGL 渲染等手段,在保证视觉质量的同时,实现了流畅的交互体验。", - "section3Title": "最终成果", - "section3Content": "项目上线后获得了广泛好评,赢得了多个设计奖项。用户平均停留时间超过 5 分钟,远高于行业平均水平。" - }, - "new-tools-integration": { - "content": "为了更好地服务客户,我们不断扩充和完善我们的工具箱。最近,我们新增了多款实用工具,涵盖设计、开发、协作等多个领域。", - "section1Title": "设计工具升级", - "section1Content": "我们引入了最新的设计协作平台,支持实时多人编辑、版本管理、设计系统集成等功能。设计师和开发者可以在同一个平台上无缝协作。", - "quote": "工欲善其事,必先利其器。好的工具能够大幅提升团队效率。", - "section2Title": "开发工具增强", - "section2Content": "新增了自动化测试框架、性能监控工具、代码质量检查等开发工具。这些工具帮助我们在开发过程中及时发现和解决问题,保证代码质量。", - "section3Title": "协作工具优化", - "section3Content": "我们升级了项目管理平台,新增了看板视图、时间追踪、资源分配等功能。项目经理可以更直观地掌控项目进度,团队成员可以更高效地协作。" - } - } + "relatedArticles": "相关文章" } }, "auth": { @@ -584,7 +426,8 @@ "date": "时间", "delivered": "已送达邮箱", "notDelivered": "未送达(SMTP 未配置)" - } + }, + "adminEntry": "进入后台管理" }, "comments": { "title": "评论", diff --git a/nuxt.config.ts b/nuxt.config.ts index 328459d..59b2ce4 100755 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -32,6 +32,7 @@ export default defineNuxtConfig({ smtpFrom: '', contactTo: '', adminEmails: '', + adminInitialPassword: '', public: { // 客户端可见(环境变量:NUXT_PUBLIC_SITE_URL),用于 sitemap/robots/og 等绝对链接 siteUrl: '', diff --git a/scripts/generate-seed.mjs b/scripts/generate-seed.mjs new file mode 100644 index 0000000..948fcfa --- /dev/null +++ b/scripts/generate-seed.mjs @@ -0,0 +1,144 @@ +/** + * 生成 server/utils/seed.ts(一次性工具)。 + * + * 从当前 i18n 文案 + 内容元数据转录出 articles/works 双语种子数据, + * 供 DB 初始化时灌入,保证站点初始内容与改造前一致。 + * + * 用法: node scripts/generate-seed.mjs + */ +import { readFileSync, writeFileSync } from 'node:fs' + +const zh = JSON.parse(readFileSync('i18n/locales/zh.json', 'utf8')) +const en = JSON.parse(readFileSync('i18n/locales/en.json', 'utf8')) + +// ---------- 动态元数据(与原 app/data/news.ts 一致) ---------- +const articleMeta = [ + { slug: 'design-trends-2026', category: 'insights', date: '2026-05-28', readTime: 5, author: 'ArcticNewOne', image: 'https://picsum.photos/id/1/800/500' }, + { slug: 'forma-digital-launch', category: 'projects', date: '2026-05-15', readTime: 3, author: 'ArcticNewOne', image: 'https://picsum.photos/id/201/800/500' }, + { slug: 'studio-expansion', category: 'announcements', date: '2026-05-10', readTime: 2, author: 'ArcticNewOne', image: 'https://picsum.photos/id/164/800/500' }, + { slug: 'ux-research-methods', category: 'insights', date: '2026-04-28', readTime: 7, author: 'ArcticNewOne', image: 'https://picsum.photos/id/180/800/500' }, + { slug: 'bold-moves-case-study', category: 'projects', date: '2026-04-20', readTime: 6, author: 'ArcticNewOne', image: 'https://picsum.photos/id/119/800/500' }, + { slug: 'new-tools-integration', category: 'announcements', date: '2026-04-12', readTime: 4, author: 'ArcticNewOne', image: 'https://picsum.photos/id/326/800/500' }, +] + +// ---------- 作品元数据(与原 app/data/work.ts 一致) ---------- +const workMeta = [ + { slug: 'forma-digital', category: 'webDesign', year: '2026', tags: ['Web Design', 'E-commerce', 'React'], image: 'https://picsum.photos/id/201/1200/800', gallery: ['https://picsum.photos/id/201/800/600', 'https://picsum.photos/id/202/800/600', 'https://picsum.photos/id/203/800/600', 'https://picsum.photos/id/204/800/600'], url: null }, + { slug: 'one-step', category: 'branding', year: '2024', tags: ['Branding', 'Marketing', 'UI/UX'], image: 'https://picsum.photos/id/180/1200/800', gallery: ['https://picsum.photos/id/180/800/600', 'https://picsum.photos/id/181/800/600', 'https://picsum.photos/id/182/800/600', 'https://picsum.photos/id/183/800/600'], url: null }, + { slug: 'nero-vision', category: 'development', year: '2025', tags: ['Development', 'Vue.js', 'Node.js'], image: 'https://picsum.photos/id/119/1200/800', gallery: ['https://picsum.photos/id/119/800/600', 'https://picsum.photos/id/120/800/600', 'https://picsum.photos/id/121/800/600', 'https://picsum.photos/id/122/800/600'], url: null }, + { slug: 'bold-moves', category: 'webDesign', year: '2024', tags: ['Web Design', '3D', 'Three.js'], image: 'https://picsum.photos/id/164/1200/800', gallery: ['https://picsum.photos/id/164/800/600', 'https://picsum.photos/id/165/800/600', 'https://picsum.photos/id/166/800/600', 'https://picsum.photos/id/167/800/600'], url: null }, + { slug: 'echo-labs', category: 'branding', year: '2025', tags: ['Branding', 'Visual Identity', 'Corporate'], image: 'https://picsum.photos/id/101/1200/800', gallery: ['https://picsum.photos/id/101/800/600', 'https://picsum.photos/id/102/800/600', 'https://picsum.photos/id/103/800/600', 'https://picsum.photos/id/104/800/600'], url: null }, + { slug: 'flux-api', category: 'development', year: '2025', tags: ['Development', 'API', 'Python'], image: 'https://picsum.photos/id/326/1200/800', gallery: ['https://picsum.photos/id/326/800/600', 'https://picsum.photos/id/327/800/600', 'https://picsum.photos/id/328/800/600', 'https://picsum.photos/id/329/800/600'], url: null }, +] + +// ---------- 文章正文块(从 i18n 转录) ---------- +function articleBlocks(locale, slug) { + const d = locale.detail.items[slug] + return [ + { type: 'paragraph', text: d.content }, + { type: 'heading', text: d.section1Title }, + { type: 'paragraph', text: d.section1Content }, + { type: 'quote', text: d.quote }, + { type: 'heading', text: d.section2Title }, + { type: 'paragraph', text: d.section2Content }, + { type: 'heading', text: d.section3Title }, + { type: 'paragraph', text: d.section3Content }, + ] +} + +const articles = articleMeta.map((m) => ({ + slug: m.slug, + category: m.category, + titleZh: zh.news.items[m.slug].title, + titleEn: en.news.items[m.slug].title, + excerptZh: zh.news.items[m.slug].excerpt, + excerptEn: en.news.items[m.slug].excerpt, + contentZh: articleBlocks(zh.news, m.slug), + contentEn: articleBlocks(en.news, m.slug), + image: m.image, + date: m.date, + readTime: m.readTime, + author: m.author, + published: 1, +})) + +const works = workMeta.map((m) => ({ + slug: m.slug, + category: m.category, + titleZh: zh.work.items[m.slug].title, + titleEn: en.work.items[m.slug].title, + descriptionZh: zh.work.items[m.slug].description, + descriptionEn: en.work.items[m.slug].description, + overviewZh: zh.work.detail.items[m.slug].overview, + overviewEn: en.work.detail.items[m.slug].overview, + challengeZh: zh.work.detail.items[m.slug].challenge, + challengeEn: en.work.detail.items[m.slug].challenge, + solutionZh: zh.work.detail.items[m.slug].solution, + solutionEn: en.work.detail.items[m.slug].solution, + clientZh: zh.work.detail.items[m.slug].client, + clientEn: en.work.detail.items[m.slug].client, + durationZh: zh.work.detail.items[m.slug].duration, + durationEn: en.work.detail.items[m.slug].duration, + year: m.year, + tags: m.tags, + image: m.image, + gallery: m.gallery, + url: m.url, + published: 1, +})) + +const out = `/** + * 种子数据(由 scripts/generate-seed.mjs 生成,勿手改)。 + * 站点初始内容:6 篇动态 + 6 个作品(中英双语)。 + * DB 初始化(migrate)时若对应表为空则自动灌入。 + */ +import type { ArticleBlock } from './db' + +export interface ArticleSeed { + slug: string + category: 'insights' | 'projects' | 'announcements' + titleZh: string + titleEn: string + excerptZh: string + excerptEn: string + contentZh: ArticleBlock[] + contentEn: ArticleBlock[] + image: string + date: string + readTime: number + author: string + published: number +} + +export interface WorkSeed { + slug: string + category: 'webDesign' | 'branding' | 'development' + titleZh: string + titleEn: string + descriptionZh: string + descriptionEn: string + overviewZh: string + overviewEn: string + challengeZh: string + challengeEn: string + solutionZh: string + solutionEn: string + clientZh: string + clientEn: string + durationZh: string + durationEn: string + year: string + tags: string[] + image: string + gallery: string[] + url: string | null + published: number +} + +export const articlesSeed: ArticleSeed[] = ${JSON.stringify(articles, null, 2)} + +export const worksSeed: WorkSeed[] = ${JSON.stringify(works, null, 2)} +` + +writeFileSync('server/utils/seed.ts', out) +console.log(`seed.ts generated: ${articles.length} articles, ${works.length} works`) diff --git a/server/api/account/admin.get.ts b/server/api/account/admin.get.ts deleted file mode 100644 index 70bad32..0000000 --- a/server/api/account/admin.get.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { requireAdmin } from '../../utils/auth' -import { getDb } from '../../utils/db' - -/** - * 管理员收件箱:联系留言 + 邮箱订阅(仅 admin 可见) - */ -export default defineEventHandler((event) => { - requireAdmin(event) - const db = getDb() - - const contacts = db - .prepare( - 'SELECT id, name, email, subject, message, delivered, created_at AS createdAt FROM contacts ORDER BY created_at DESC', - ) - .all() as Array<{ - id: number - name: string - email: string - subject: string - message: string - delivered: number - createdAt: string - }> - - const subscribers = db - .prepare('SELECT id, email, created_at AS createdAt FROM subscribers ORDER BY created_at DESC') - .all() as Array<{ id: number; email: string; createdAt: string }> - - return { contacts, subscribers } -}) diff --git a/server/api/admin/articles.get.ts b/server/api/admin/articles.get.ts new file mode 100644 index 0000000..6c922d1 --- /dev/null +++ b/server/api/admin/articles.get.ts @@ -0,0 +1,10 @@ +import { requireAdmin } from '../../utils/auth' +import { listArticles } from '../../utils/content' + +/** + * 后台动态列表(含未发布) + */ +export default defineEventHandler((event) => { + requireAdmin(event) + return { articles: listArticles({ publishedOnly: false }) } +}) diff --git a/server/api/admin/articles.post.ts b/server/api/admin/articles.post.ts new file mode 100644 index 0000000..0c8611e --- /dev/null +++ b/server/api/admin/articles.post.ts @@ -0,0 +1,52 @@ +import { readBody, createError } from 'h3' +import { requireAdmin } from '../../utils/auth' +import { getDb } from '../../utils/db' +import { getArticleBySlug } from '../../utils/content' +import { normalizeSlug, isValidSlug, isValidArticleCategory, normalizeBlocks } from '../../utils/validateContent' + +/** + * 后台新增动态 + */ +export default defineEventHandler(async (event) => { + requireAdmin(event) + const body = await readBody(event) + const db = getDb() + + const slug = normalizeSlug(body?.slug) + if (!isValidSlug(slug)) { + throw createError({ statusCode: 400, message: 'slug 需为 2-64 位小写字母/数字/中划线', data: { code: 'VALIDATION_ERROR' } }) + } + if (!isValidArticleCategory(body?.category)) { + throw createError({ statusCode: 400, message: '分类不合法', data: { code: 'VALIDATION_ERROR' } }) + } + const titleZh = String(body?.titleZh ?? '').trim() + const titleEn = String(body?.titleEn ?? '').trim() + if (!titleZh || !titleEn) { + throw createError({ statusCode: 400, message: '中英文标题不能为空', data: { code: 'VALIDATION_ERROR' } }) + } + if (getArticleBySlug(slug, { publishedOnly: false })) { + throw createError({ statusCode: 400, message: 'slug 已存在', data: { code: 'SLUG_TAKEN' } }) + } + + db.prepare( + `INSERT INTO articles + (slug, category, title_zh, title_en, excerpt_zh, excerpt_en, content_zh, content_en, image, date, read_time, author, published, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))`, + ).run( + slug, + body.category, + titleZh, + titleEn, + String(body?.excerptZh ?? ''), + String(body?.excerptEn ?? ''), + JSON.stringify(normalizeBlocks(body?.contentZh)), + JSON.stringify(normalizeBlocks(body?.contentEn)), + body?.image ? String(body.image).trim() : null, + body?.date ? String(body.date).trim() : null, + Number(body?.readTime) || 5, + String(body?.author ?? 'ArcticNewOne').trim() || 'ArcticNewOne', + body?.published ? 1 : 0, + ) + + return { ok: true, article: getArticleBySlug(slug, { publishedOnly: false }) } +}) diff --git a/server/api/admin/articles/[id].delete.ts b/server/api/admin/articles/[id].delete.ts new file mode 100644 index 0000000..cb48417 --- /dev/null +++ b/server/api/admin/articles/[id].delete.ts @@ -0,0 +1,25 @@ +import { createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' + +/** + * 后台删除动态(连带删除其评论) + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const db = getDb() + + const row = db.prepare('SELECT slug FROM articles WHERE id = ?').get(id) as { slug: string } | undefined + if (!row) { + throw createError({ statusCode: 404, message: '动态不存在', data: { code: 'NOT_FOUND' } }) + } + + const tx = db.transaction(() => { + db.prepare('DELETE FROM comments WHERE news_slug = ?').run(row.slug) + db.prepare('DELETE FROM articles WHERE id = ?').run(id) + }) + tx() + + return { ok: true } +}) diff --git a/server/api/admin/articles/[id].patch.ts b/server/api/admin/articles/[id].patch.ts new file mode 100644 index 0000000..69ed000 --- /dev/null +++ b/server/api/admin/articles/[id].patch.ts @@ -0,0 +1,82 @@ +import { readBody, createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' +import { getArticleBySlug } from '../../../utils/content' +import { normalizeSlug, isValidSlug, isValidArticleCategory, normalizeBlocks } from '../../../utils/validateContent' + +/** + * 后台更新动态(部分字段) + */ +export default defineEventHandler(async (event) => { + requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const body = await readBody(event) + const db = getDb() + + const existing = db.prepare('SELECT slug FROM articles WHERE id = ?').get(id) as { slug: string } | undefined + if (!existing) { + throw createError({ statusCode: 404, message: '动态不存在', data: { code: 'NOT_FOUND' } }) + } + + const sets: string[] = [] + const params: unknown[] = [] + + if (body?.slug !== undefined) { + const slug = normalizeSlug(body.slug) + if (!isValidSlug(slug)) { + throw createError({ statusCode: 400, message: 'slug 需为 2-64 位小写字母/数字/中划线', data: { code: 'VALIDATION_ERROR' } }) + } + const taken = db.prepare('SELECT id FROM articles WHERE slug = ? AND id != ?').get(slug, id) + if (taken) { + throw createError({ statusCode: 400, message: 'slug 已存在', data: { code: 'SLUG_TAKEN' } }) + } + sets.push('slug = ?'); params.push(slug) + } + if (body?.category !== undefined) { + if (!isValidArticleCategory(body.category)) { + throw createError({ statusCode: 400, message: '分类不合法', data: { code: 'VALIDATION_ERROR' } }) + } + sets.push('category = ?'); params.push(body.category) + } + for (const field of ['titleZh', 'titleEn', 'excerptZh', 'excerptEn', 'image', 'date', 'author'] as const) { + if (body?.[field] !== undefined) { + if (field === 'titleZh' || field === 'titleEn') { + if (!String(body[field]).trim()) { + throw createError({ statusCode: 400, message: '中英文标题不能为空', data: { code: 'VALIDATION_ERROR' } }) + } + } + sets.push(fieldToCol(field) + ' = ?'); params.push(String(body[field]).trim()) + } + } + if (body?.readTime !== undefined) { + sets.push('read_time = ?'); params.push(Number(body.readTime) || 5) + } + if (body?.published !== undefined) { + sets.push('published = ?'); params.push(body.published ? 1 : 0) + } + if (body?.contentZh !== undefined) { + sets.push('content_zh = ?'); params.push(JSON.stringify(normalizeBlocks(body.contentZh))) + } + if (body?.contentEn !== undefined) { + sets.push('content_en = ?'); params.push(JSON.stringify(normalizeBlocks(body.contentEn))) + } + + if (sets.length === 0) { + throw createError({ statusCode: 400, message: '没有可更新的字段', data: { code: 'VALIDATION_ERROR' } }) + } + + sets.push("updated_at = datetime('now')") + db.prepare(`UPDATE articles SET ${sets.join(', ')} WHERE id = ?`).run(...params, id) + + const row = db.prepare('SELECT slug FROM articles WHERE id = ?').get(id) as { slug: string } + return { ok: true, article: getArticleBySlug(row.slug, { publishedOnly: false }) } +}) + +function fieldToCol(field: string): string { + const map: Record = { + titleZh: 'title_zh', titleEn: 'title_en', + excerptZh: 'excerpt_zh', excerptEn: 'excerpt_en', + image: 'image', date: 'date', author: 'author', + } + return map[field] +} diff --git a/server/api/admin/comments.get.ts b/server/api/admin/comments.get.ts new file mode 100644 index 0000000..b10e744 --- /dev/null +++ b/server/api/admin/comments.get.ts @@ -0,0 +1,18 @@ +import { requireAdmin } from '../../utils/auth' +import { getDb } from '../../utils/db' + +/** + * 后台全站评论列表(含文章 slug 与作者) + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const comments = getDb() + .prepare( + `SELECT c.id, c.news_slug AS newsSlug, c.content, c.created_at AS createdAt, u.username + FROM comments c + JOIN users u ON u.id = c.user_id + ORDER BY c.created_at DESC`, + ) + .all() + return { comments } +}) diff --git a/server/api/admin/comments/[id].delete.ts b/server/api/admin/comments/[id].delete.ts new file mode 100644 index 0000000..b5e44c9 --- /dev/null +++ b/server/api/admin/comments/[id].delete.ts @@ -0,0 +1,18 @@ +import { createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' + +/** + * 后台删除评论 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const db = getDb() + const target = db.prepare('SELECT id FROM comments WHERE id = ?').get(id) + if (!target) { + throw createError({ statusCode: 404, message: '评论不存在', data: { code: 'NOT_FOUND' } }) + } + db.prepare('DELETE FROM comments WHERE id = ?').run(id) + return { ok: true } +}) diff --git a/server/api/admin/contacts.get.ts b/server/api/admin/contacts.get.ts new file mode 100644 index 0000000..65961b3 --- /dev/null +++ b/server/api/admin/contacts.get.ts @@ -0,0 +1,13 @@ +import { requireAdmin } from '../../utils/auth' +import { getDb } from '../../utils/db' + +/** + * 后台联系消息列表 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const contacts = getDb() + .prepare('SELECT id, name, email, subject, message, delivered, created_at AS createdAt FROM contacts ORDER BY created_at DESC') + .all() + return { contacts } +}) diff --git a/server/api/admin/contacts/[id].delete.ts b/server/api/admin/contacts/[id].delete.ts new file mode 100644 index 0000000..2eeb142 --- /dev/null +++ b/server/api/admin/contacts/[id].delete.ts @@ -0,0 +1,18 @@ +import { createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' + +/** + * 后台删除联系消息 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const db = getDb() + const target = db.prepare('SELECT id FROM contacts WHERE id = ?').get(id) + if (!target) { + throw createError({ statusCode: 404, message: '消息不存在', data: { code: 'NOT_FOUND' } }) + } + db.prepare('DELETE FROM contacts WHERE id = ?').run(id) + return { ok: true } +}) diff --git a/server/api/admin/stats.get.ts b/server/api/admin/stats.get.ts new file mode 100644 index 0000000..83a6ae9 --- /dev/null +++ b/server/api/admin/stats.get.ts @@ -0,0 +1,20 @@ +import { requireAdmin } from '../../utils/auth' +import { getDb } from '../../utils/db' +import { getContentStats } from '../../utils/content' + +/** + * 后台 Dashboard 统计 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const db = getDb() + const one = (sql: string) => (db.prepare(sql).get() as { c: number }).c + return { + ...getContentStats(), + users: one('SELECT COUNT(*) AS c FROM users'), + comments: one('SELECT COUNT(*) AS c FROM comments'), + contacts: one('SELECT COUNT(*) AS c FROM contacts'), + subscribers: one('SELECT COUNT(*) AS c FROM subscribers'), + favorites: one('SELECT COUNT(*) AS c FROM favorites'), + } +}) diff --git a/server/api/admin/subscribers.get.ts b/server/api/admin/subscribers.get.ts new file mode 100644 index 0000000..c5bd49d --- /dev/null +++ b/server/api/admin/subscribers.get.ts @@ -0,0 +1,13 @@ +import { requireAdmin } from '../../utils/auth' +import { getDb } from '../../utils/db' + +/** + * 后台订阅列表 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const subscribers = getDb() + .prepare('SELECT id, email, created_at AS createdAt FROM subscribers ORDER BY created_at DESC') + .all() + return { subscribers } +}) diff --git a/server/api/admin/subscribers/[id].delete.ts b/server/api/admin/subscribers/[id].delete.ts new file mode 100644 index 0000000..1f42424 --- /dev/null +++ b/server/api/admin/subscribers/[id].delete.ts @@ -0,0 +1,18 @@ +import { createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' + +/** + * 后台删除订阅 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const db = getDb() + const target = db.prepare('SELECT id FROM subscribers WHERE id = ?').get(id) + if (!target) { + throw createError({ statusCode: 404, message: '订阅不存在', data: { code: 'NOT_FOUND' } }) + } + db.prepare('DELETE FROM subscribers WHERE id = ?').run(id) + return { ok: true } +}) diff --git a/server/api/admin/subscribers/export.get.ts b/server/api/admin/subscribers/export.get.ts new file mode 100644 index 0000000..c2422ce --- /dev/null +++ b/server/api/admin/subscribers/export.get.ts @@ -0,0 +1,23 @@ +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' + +/** + * 导出订阅 CSV(UTF-8 BOM,兼容 Excel) + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const rows = getDb() + .prepare('SELECT email, created_at AS createdAt FROM subscribers ORDER BY created_at DESC') + .all() as Array<{ email: string; createdAt: string }> + + const escape = (v: string) => `"${String(v).replace(/"/g, '""')}"` + const lines = ['email,created_at', ...rows.map((r) => `${escape(r.email)},${escape(r.createdAt)}`)] + const csv = '' + lines.join('\n') + + return new Response(csv, { + headers: { + 'Content-Type': 'text/csv; charset=utf-8', + 'Content-Disposition': `attachment; filename="subscribers-${new Date().toISOString().slice(0, 10)}.csv"`, + }, + }) +}) diff --git a/server/api/admin/upload.post.ts b/server/api/admin/upload.post.ts new file mode 100644 index 0000000..d3c5742 --- /dev/null +++ b/server/api/admin/upload.post.ts @@ -0,0 +1,46 @@ +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' + +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', +} + +/** + * 后台图片上传 -> 保存到 PVC 的 uploads 目录(/data/uploads), + * 通过 /uploads/ 对外提供。 + */ +export default defineEventHandler(async (event) => { + requireAdmin(event) + + const parts = await readMultipartFormData(event) + const file = parts?.find((p) => p.name === 'file' && p.data?.length) + 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) { + 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' } }) + } + + const name = `${Date.now()}-${randomBytes(6).toString('hex')}.${ext}` + const dir = join(dirname(getConfig().dbPath), 'uploads') + mkdirSync(dir, { recursive: true }) + writeFileSync(join(dir, name), file.data) + + return { ok: true, url: `/uploads/${name}` } +}) diff --git a/server/api/admin/users.get.ts b/server/api/admin/users.get.ts new file mode 100644 index 0000000..39efa57 --- /dev/null +++ b/server/api/admin/users.get.ts @@ -0,0 +1,13 @@ +import { requireAdmin } from '../../utils/auth' +import { getDb } from '../../utils/db' + +/** + * 后台用户列表 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const users = getDb() + .prepare('SELECT id, username, email, phone, role, created_at AS createdAt FROM users ORDER BY id DESC') + .all() + return { users } +}) diff --git a/server/api/admin/users/[id].delete.ts b/server/api/admin/users/[id].delete.ts new file mode 100644 index 0000000..5b235f9 --- /dev/null +++ b/server/api/admin/users/[id].delete.ts @@ -0,0 +1,22 @@ +import { createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' + +/** + * 后台删除用户(连带删除其会话/评论/收藏) + */ +export default defineEventHandler((event) => { + const me = requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const db = getDb() + + if (me.id === id) { + throw createError({ statusCode: 400, message: '不能删除自己的账号', data: { code: 'VALIDATION_ERROR' } }) + } + const target = db.prepare('SELECT id FROM users WHERE id = ?').get(id) + if (!target) { + throw createError({ statusCode: 404, message: '用户不存在', data: { code: 'NOT_FOUND' } }) + } + db.prepare('DELETE FROM users WHERE id = ?').run(id) // 外键级联:sessions/comments/favorites + return { ok: true } +}) diff --git a/server/api/admin/users/[id].patch.ts b/server/api/admin/users/[id].patch.ts new file mode 100644 index 0000000..9cb9aa9 --- /dev/null +++ b/server/api/admin/users/[id].patch.ts @@ -0,0 +1,28 @@ +import { readBody, createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' + +/** + * 后台更新用户(角色切换) + */ +export default defineEventHandler(async (event) => { + const me = requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const body = await readBody(event) + const db = getDb() + + if (me.id === id) { + throw createError({ statusCode: 400, message: '不能修改自己的角色', data: { code: 'VALIDATION_ERROR' } }) + } + const target = db.prepare('SELECT id FROM users WHERE id = ?').get(id) + if (!target) { + throw createError({ statusCode: 404, message: '用户不存在', data: { code: 'NOT_FOUND' } }) + } + if (body?.role !== undefined) { + if (!['user', 'admin'].includes(body.role)) { + throw createError({ statusCode: 400, message: '角色不合法', data: { code: 'VALIDATION_ERROR' } }) + } + db.prepare('UPDATE users SET role = ? WHERE id = ?').run(body.role, id) + } + return { ok: true } +}) diff --git a/server/api/admin/works.get.ts b/server/api/admin/works.get.ts new file mode 100644 index 0000000..bcb580b --- /dev/null +++ b/server/api/admin/works.get.ts @@ -0,0 +1,10 @@ +import { requireAdmin } from '../../utils/auth' +import { listWorks } from '../../utils/content' + +/** + * 后台作品列表(含未发布) + */ +export default defineEventHandler((event) => { + requireAdmin(event) + return { works: listWorks({ publishedOnly: false }) } +}) diff --git a/server/api/admin/works.post.ts b/server/api/admin/works.post.ts new file mode 100644 index 0000000..019986e --- /dev/null +++ b/server/api/admin/works.post.ts @@ -0,0 +1,69 @@ +import { readBody, createError } from 'h3' +import { requireAdmin } from '../../utils/auth' +import { getDb } from '../../utils/db' +import { getWorkBySlug } from '../../utils/content' +import { + normalizeSlug, + isValidSlug, + isValidWorkCategory, + normalizeTags, + normalizeGallery, +} from '../../utils/validateContent' + +/** + * 后台新增作品 + */ +export default defineEventHandler(async (event) => { + requireAdmin(event) + const body = await readBody(event) + const db = getDb() + + const slug = normalizeSlug(body?.slug) + if (!isValidSlug(slug)) { + throw createError({ statusCode: 400, message: 'slug 需为 2-64 位小写字母/数字/中划线', data: { code: 'VALIDATION_ERROR' } }) + } + if (!isValidWorkCategory(body?.category)) { + throw createError({ statusCode: 400, message: '分类不合法', data: { code: 'VALIDATION_ERROR' } }) + } + const titleZh = String(body?.titleZh ?? '').trim() + const titleEn = String(body?.titleEn ?? '').trim() + if (!titleZh || !titleEn) { + throw createError({ statusCode: 400, message: '中英文标题不能为空', data: { code: 'VALIDATION_ERROR' } }) + } + if (getWorkBySlug(slug, { publishedOnly: false })) { + throw createError({ statusCode: 400, message: 'slug 已存在', data: { code: 'SLUG_TAKEN' } }) + } + + db.prepare( + `INSERT INTO works + (slug, category, title_zh, title_en, description_zh, description_en, + overview_zh, overview_en, challenge_zh, challenge_en, solution_zh, solution_en, + client_zh, client_en, duration_zh, duration_en, year, tags, image, gallery, url, published, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))`, + ).run( + slug, + body.category, + titleZh, + titleEn, + String(body?.descriptionZh ?? ''), + String(body?.descriptionEn ?? ''), + String(body?.overviewZh ?? ''), + String(body?.overviewEn ?? ''), + String(body?.challengeZh ?? ''), + String(body?.challengeEn ?? ''), + String(body?.solutionZh ?? ''), + String(body?.solutionEn ?? ''), + String(body?.clientZh ?? ''), + String(body?.clientEn ?? ''), + String(body?.durationZh ?? ''), + String(body?.durationEn ?? ''), + String(body?.year ?? ''), + JSON.stringify(normalizeTags(body?.tags)), + body?.image ? String(body.image).trim() : null, + JSON.stringify(normalizeGallery(body?.gallery)), + body?.url ? String(body.url).trim() : null, + body?.published ? 1 : 0, + ) + + return { ok: true, work: getWorkBySlug(slug, { publishedOnly: false }) } +}) diff --git a/server/api/admin/works/[id].delete.ts b/server/api/admin/works/[id].delete.ts new file mode 100644 index 0000000..b692945 --- /dev/null +++ b/server/api/admin/works/[id].delete.ts @@ -0,0 +1,25 @@ +import { createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' + +/** + * 后台删除作品(连带清理用户收藏) + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const db = getDb() + + const row = db.prepare('SELECT slug FROM works WHERE id = ?').get(id) as { slug: string } | undefined + if (!row) { + throw createError({ statusCode: 404, message: '作品不存在', data: { code: 'NOT_FOUND' } }) + } + + const tx = db.transaction(() => { + db.prepare('DELETE FROM favorites WHERE work_slug = ?').run(row.slug) + db.prepare('DELETE FROM works WHERE id = ?').run(id) + }) + tx() + + return { ok: true } +}) diff --git a/server/api/admin/works/[id].patch.ts b/server/api/admin/works/[id].patch.ts new file mode 100644 index 0000000..242ab13 --- /dev/null +++ b/server/api/admin/works/[id].patch.ts @@ -0,0 +1,95 @@ +import { readBody, createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' +import { getWorkBySlug } from '../../../utils/content' +import { + normalizeSlug, + isValidSlug, + isValidWorkCategory, + normalizeTags, + normalizeGallery, +} from '../../../utils/validateContent' + +/** + * 后台更新作品(部分字段) + */ +export default defineEventHandler(async (event) => { + requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const body = await readBody(event) + const db = getDb() + + const existing = db.prepare('SELECT slug FROM works WHERE id = ?').get(id) as { slug: string } | undefined + if (!existing) { + throw createError({ statusCode: 404, message: '作品不存在', data: { code: 'NOT_FOUND' } }) + } + + const sets: string[] = [] + const params: unknown[] = [] + + if (body?.slug !== undefined) { + const slug = normalizeSlug(body.slug) + if (!isValidSlug(slug)) { + throw createError({ statusCode: 400, message: 'slug 需为 2-64 位小写字母/数字/中划线', data: { code: 'VALIDATION_ERROR' } }) + } + const taken = db.prepare('SELECT id FROM works WHERE slug = ? AND id != ?').get(slug, id) + if (taken) { + throw createError({ statusCode: 400, message: 'slug 已存在', data: { code: 'SLUG_TAKEN' } }) + } + sets.push('slug = ?'); params.push(slug) + } + if (body?.category !== undefined) { + if (!isValidWorkCategory(body.category)) { + throw createError({ statusCode: 400, message: '分类不合法', data: { code: 'VALIDATION_ERROR' } }) + } + sets.push('category = ?'); params.push(body.category) + } + for (const field of [ + 'titleZh', 'titleEn', 'descriptionZh', 'descriptionEn', + 'overviewZh', 'overviewEn', 'challengeZh', 'challengeEn', + 'solutionZh', 'solutionEn', 'clientZh', 'clientEn', + 'durationZh', 'durationEn', 'year', 'image', 'url', + ] as const) { + if (body?.[field] !== undefined) { + if (field === 'titleZh' || field === 'titleEn') { + if (!String(body[field]).trim()) { + throw createError({ statusCode: 400, message: '中英文标题不能为空', data: { code: 'VALIDATION_ERROR' } }) + } + } + sets.push(fieldToCol(field) + ' = ?'); params.push(String(body[field]).trim()) + } + } + if (body?.tags !== undefined) { + sets.push('tags = ?'); params.push(JSON.stringify(normalizeTags(body.tags))) + } + if (body?.gallery !== undefined) { + sets.push('gallery = ?'); params.push(JSON.stringify(normalizeGallery(body.gallery))) + } + if (body?.published !== undefined) { + sets.push('published = ?'); params.push(body.published ? 1 : 0) + } + + if (sets.length === 0) { + throw createError({ statusCode: 400, message: '没有可更新的字段', data: { code: 'VALIDATION_ERROR' } }) + } + + sets.push("updated_at = datetime('now')") + db.prepare(`UPDATE works SET ${sets.join(', ')} WHERE id = ?`).run(...params, id) + + const row = db.prepare('SELECT slug FROM works WHERE id = ?').get(id) as { slug: string } + return { ok: true, work: getWorkBySlug(row.slug, { publishedOnly: false }) } +}) + +function fieldToCol(field: string): string { + const map: Record = { + titleZh: 'title_zh', titleEn: 'title_en', + descriptionZh: 'description_zh', descriptionEn: 'description_en', + overviewZh: 'overview_zh', overviewEn: 'overview_en', + challengeZh: 'challenge_zh', challengeEn: 'challenge_en', + solutionZh: 'solution_zh', solutionEn: 'solution_en', + clientZh: 'client_zh', clientEn: 'client_en', + durationZh: 'duration_zh', durationEn: 'duration_en', + year: 'year', image: 'image', url: 'url', + } + return map[field] +} diff --git a/server/api/auth/register.post.ts b/server/api/auth/register.post.ts index 07f78a6..e995b8e 100644 --- a/server/api/auth/register.post.ts +++ b/server/api/auth/register.post.ts @@ -1,6 +1,7 @@ import { readBody, createError } from 'h3' import { getDb } from '../../utils/db' import { hashPassword, createSession, setSessionCookie, toPublicUser, type UserRow } from '../../utils/auth' +import { isAdminEmail } from '../../utils/config' import { isValidUsername, isValidEmail, isValidPassword, isValidPhone } from '../../utils/validation' /** @@ -39,9 +40,11 @@ export default defineEventHandler(async (event) => { } const passwordHash = await hashPassword(password) + // 管理员邮箱白名单命中者自动授予 admin 角色(后续可后台切换) + const role = isAdminEmail(email) ? 'admin' : 'user' const info = db - .prepare('INSERT INTO users (username, email, phone, password_hash) VALUES (?, ?, ?, ?)') - .run(username, email, phone || null, passwordHash) + .prepare('INSERT INTO users (username, email, phone, password_hash, role) VALUES (?, ?, ?, ?, ?)') + .run(username, email, phone || null, passwordHash, role) const user = db .prepare('SELECT id, username, email, phone, role, created_at FROM users WHERE id = ?') diff --git a/server/api/comments.get.ts b/server/api/comments.get.ts index 0c74ee5..295e91c 100644 --- a/server/api/comments.get.ts +++ b/server/api/comments.get.ts @@ -1,6 +1,6 @@ import { getQuery, createError } from 'h3' import { getDb } from '../utils/db' -import { newsBySlug } from '../../app/data/news' +import { getArticleBySlug } from '../utils/content' /** * 指定新闻的评论列表(公开) @@ -9,7 +9,7 @@ export default defineEventHandler((event) => { const query = getQuery(event) const newsSlug = String(query?.newsSlug ?? '') - if (!newsBySlug[newsSlug]) { + if (!getArticleBySlug(newsSlug, { publishedOnly: false })) { throw createError({ statusCode: 404, message: '文章不存在', data: { code: 'NOT_FOUND' } }) } diff --git a/server/api/comments.post.ts b/server/api/comments.post.ts index 5d93a14..fb0358a 100644 --- a/server/api/comments.post.ts +++ b/server/api/comments.post.ts @@ -1,7 +1,7 @@ import { readBody, createError } from 'h3' import { requireUser } from '../utils/auth' import { getDb } from '../utils/db' -import { newsBySlug } from '../../app/data/news' +import { getArticleBySlug } from '../utils/content' /** * 发表评论(需登录) @@ -12,7 +12,7 @@ export default defineEventHandler(async (event) => { const newsSlug = String(body?.newsSlug ?? '') const content = String(body?.content ?? '').trim() - if (!newsBySlug[newsSlug]) { + if (!getArticleBySlug(newsSlug, { publishedOnly: false })) { throw createError({ statusCode: 400, message: '未知的文章', data: { code: 'VALIDATION_ERROR' } }) } if (!content) { diff --git a/server/api/favorites.post.ts b/server/api/favorites.post.ts index f24ab4f..e641472 100644 --- a/server/api/favorites.post.ts +++ b/server/api/favorites.post.ts @@ -1,7 +1,7 @@ import { readBody, createError } from 'h3' import { requireUser } from '../utils/auth' import { getDb } from '../utils/db' -import { workBySlug } from '../../app/data/work' +import { getWorkBySlug } from '../utils/content' /** * 收藏作品(幂等) @@ -11,7 +11,7 @@ export default defineEventHandler(async (event) => { const body = await readBody(event) const workSlug = String(body?.workSlug ?? '') - if (!workBySlug[workSlug]) { + if (!getWorkBySlug(workSlug, { publishedOnly: false })) { throw createError({ statusCode: 400, message: '未知的作品', data: { code: 'VALIDATION_ERROR' } }) } diff --git a/server/api/news.get.ts b/server/api/news.get.ts new file mode 100644 index 0000000..6f5bb79 --- /dev/null +++ b/server/api/news.get.ts @@ -0,0 +1,8 @@ +import { listArticles } from '../utils/content' + +/** + * 动态列表(前台,仅已发布) + */ +export default defineEventHandler(() => { + return { articles: listArticles({ publishedOnly: true }) } +}) diff --git a/server/api/news/[slug].get.ts b/server/api/news/[slug].get.ts new file mode 100644 index 0000000..0142056 --- /dev/null +++ b/server/api/news/[slug].get.ts @@ -0,0 +1,14 @@ +import { createError } from 'h3' +import { getArticleBySlug } from '../../utils/content' + +/** + * 动态详情(前台,仅已发布) + */ +export default defineEventHandler((event) => { + const slug = getRouterParam(event, 'slug') ?? '' + const article = getArticleBySlug(slug, { publishedOnly: true }) + if (!article) { + throw createError({ statusCode: 404, message: '文章不存在', data: { code: 'NOT_FOUND' } }) + } + return { article } +}) diff --git a/server/api/work.get.ts b/server/api/work.get.ts new file mode 100644 index 0000000..a62e10c --- /dev/null +++ b/server/api/work.get.ts @@ -0,0 +1,8 @@ +import { listWorks } from '../utils/content' + +/** + * 作品列表(前台,仅已发布) + */ +export default defineEventHandler(() => { + return { works: listWorks({ publishedOnly: true }) } +}) diff --git a/server/api/work/[slug].get.ts b/server/api/work/[slug].get.ts new file mode 100644 index 0000000..5548f19 --- /dev/null +++ b/server/api/work/[slug].get.ts @@ -0,0 +1,14 @@ +import { createError } from 'h3' +import { getWorkBySlug } from '../../utils/content' + +/** + * 作品详情(前台,仅已发布) + */ +export default defineEventHandler((event) => { + const slug = getRouterParam(event, 'slug') ?? '' + const work = getWorkBySlug(slug, { publishedOnly: true }) + if (!work) { + throw createError({ statusCode: 404, message: '作品不存在', data: { code: 'NOT_FOUND' } }) + } + return { work } +}) diff --git a/server/routes/sitemap.xml.ts b/server/routes/sitemap.xml.ts index c493a0b..c56a1f2 100644 --- a/server/routes/sitemap.xml.ts +++ b/server/routes/sitemap.xml.ts @@ -1,13 +1,14 @@ import { getConfig } from '../utils/config' -import { newsItems } from '../../app/data/news' -import { workItems } from '../../app/data/work' +import { listArticles, listWorks } from '../utils/content' /** * 动态站点地图 /sitemap.xml。 - * 路由与数据均来自单一事实源(app/data/*),内容更新无需手工同步。 + * 内容来自数据库(后台可维护),路由自动跟随。 */ export default defineEventHandler(() => { const { siteUrl } = getConfig() + const articles = listArticles({ publishedOnly: true }) + const works = listWorks({ publishedOnly: true }) const urls: Array<{ loc: string; changefreq: string; priority: string }> = [ { loc: '/', changefreq: 'weekly', priority: '1.0' }, @@ -18,10 +19,10 @@ export default defineEventHandler(() => { { loc: '/contact', changefreq: 'monthly', priority: '0.6' }, ] - for (const item of workItems) { + for (const item of works) { urls.push({ loc: `/work/${item.slug}`, changefreq: 'monthly', priority: '0.7' }) } - for (const item of newsItems) { + for (const item of articles) { urls.push({ loc: `/news/${item.slug}`, changefreq: 'weekly', priority: '0.7' }) } diff --git a/server/routes/uploads/[...path].get.ts b/server/routes/uploads/[...path].get.ts new file mode 100644 index 0000000..06a5709 --- /dev/null +++ b/server/routes/uploads/[...path].get.ts @@ -0,0 +1,40 @@ +import { createError } from 'h3' +import { readFileSync, existsSync } from 'node:fs' +import { join, dirname, normalize } from 'node:path' +import { getConfig } from '../../utils/config' + +const MIME: Record = { + png: 'image/png', + jpg: 'image/jpeg', + jpeg: 'image/jpeg', + gif: 'image/gif', + webp: 'image/webp', + svg: 'image/svg+xml', + avif: 'image/avif', +} + +/** + * 服务上传的图片(存于 PVC uploads 目录) + */ +export default defineEventHandler((event) => { + const path = getRouterParam(event, 'path') ?? '' + const base = normalize(join(dirname(getConfig().dbPath), 'uploads')) + const filePath = normalize(join(base, path)) + + // 防目录穿越 + if (!filePath.startsWith(base + '/') && filePath !== base) { + throw createError({ statusCode: 403, message: 'Forbidden' }) + } + if (!existsSync(filePath)) { + throw createError({ statusCode: 404, message: 'Not Found' }) + } + + const ext = filePath.split('.').pop()?.toLowerCase() ?? '' + const data = readFileSync(filePath) + return new Response(new Uint8Array(data), { + headers: { + 'Content-Type': MIME[ext] || 'application/octet-stream', + 'Cache-Control': 'public, max-age=31536000, immutable', + }, + }) +}) diff --git a/server/utils/auth.ts b/server/utils/auth.ts index 505bbc2..f41550d 100644 --- a/server/utils/auth.ts +++ b/server/utils/auth.ts @@ -3,7 +3,6 @@ import { promisify } from 'node:util' import { createError, getCookie, setCookie, deleteCookie } from 'h3' import type { H3Event } from 'h3' import { getDb } from './db' -import { getConfig, isAdminEmail } from './config' const scryptAsync = promisify(scrypt) as ( password: string, @@ -54,7 +53,7 @@ export function destroySession(token: string): void { getDb().prepare('DELETE FROM sessions WHERE token = ?').run(token) } -/** 根据 token 返回有效用户(过期会话返回 null);role 随 ADMIN_EMAILS 实时判定 */ +/** 根据 token 返回有效用户(过期会话返回 null);role 以数据库存储为准(后台可切换) */ export function getSessionUser(token: string | null): UserRow | null { if (!token) return null const row = getDb() @@ -65,10 +64,7 @@ export function getSessionUser(token: string | null): UserRow | null { WHERE s.token = ? AND s.expires_at > datetime('now')`, ) .get(token) as UserRow | undefined - if (!row) return null - // 管理员角色以 ADMIN_EMAILS 配置为准(改配置即生效),数据库 role 仅作冗余存储 - row.role = isAdminEmail(row.email) ? 'admin' : 'user' - return row + return row ?? null } /** 从请求 Cookie 中解析当前登录用户 */ @@ -112,7 +108,7 @@ export function clearSessionCookie(event: H3Event): void { deleteCookie(event, SESSION_COOKIE, { path: '/' }) } -/** 返回给前端的脱敏用户对象(含 admin 角色,供个人中心展示) */ +/** 返回给前端的脱敏用户对象(含 admin 角色,供个人中心/后台展示) */ export function toPublicUser(user: UserRow): { id: number username: string @@ -121,14 +117,12 @@ export function toPublicUser(user: UserRow): { role: 'user' | 'admin' createdAt: string } { - // 管理员角色跟随 ADMIN_EMAILS 配置实时判定,保证改配置即生效 - const role: 'user' | 'admin' = isAdminEmail(user.email) ? 'admin' : 'user' return { id: user.id, username: user.username, email: user.email, phone: user.phone, - role, + role: user.role, createdAt: user.created_at, } } diff --git a/server/utils/config.ts b/server/utils/config.ts index a678d3b..b40a299 100644 --- a/server/utils/config.ts +++ b/server/utils/config.ts @@ -26,6 +26,8 @@ export interface AppConfig { } contactTo: string adminEmails: string[] + /** 首次初始化时预置 admin 账号的密码(NUXT_ADMIN_INITIAL_PASSWORD),未设则不预置 */ + adminInitialPassword: string siteUrl: string } @@ -46,6 +48,7 @@ export function getConfig(): AppConfig { .split(',') .map((s) => s.trim().toLowerCase()) .filter(Boolean), + adminInitialPassword: String((c as any).adminInitialPassword || ''), siteUrl: String((c.public as { siteUrl?: string })?.siteUrl || '').replace(/\/$/, ''), } } diff --git a/server/utils/content.ts b/server/utils/content.ts new file mode 100644 index 0000000..61af0f6 --- /dev/null +++ b/server/utils/content.ts @@ -0,0 +1,166 @@ +import { getDb, type ArticleBlock } from './db' + +/** + * 内容读取层(动态/作品)。 + * 统一负责 DB 行 -> 业务对象(解析 content/tags/gallery 的 JSON), + * 供前台内容 API、后台管理 API、sitemap 共用。 + */ + +export interface Article { + id: number + slug: string + category: 'insights' | 'projects' | 'announcements' + titleZh: string + titleEn: string + excerptZh: string + excerptEn: string + contentZh: ArticleBlock[] + contentEn: ArticleBlock[] + image: string | null + date: string | null + readTime: number + author: string + published: number + createdAt: string + updatedAt: string +} + +export interface Work { + id: number + slug: string + category: 'webDesign' | 'branding' | 'development' + titleZh: string + titleEn: string + descriptionZh: string + descriptionEn: string + overviewZh: string + overviewEn: string + challengeZh: string + challengeEn: string + solutionZh: string + solutionEn: string + clientZh: string + clientEn: string + durationZh: string + durationEn: string + year: string + tags: string[] + image: string | null + gallery: string[] + url: string | null + published: number + createdAt: string + updatedAt: string +} + +const parseJson = (value: string | null, fallback: T): T => { + if (!value) return fallback + try { + return JSON.parse(value) as T + } catch { + return fallback + } +} + +function rowToArticle(row: Record): Article { + return { + id: Number(row.id), + slug: String(row.slug), + category: row.category as Article['category'], + titleZh: String(row.title_zh), + titleEn: String(row.title_en), + excerptZh: String(row.excerpt_zh), + excerptEn: String(row.excerpt_en), + contentZh: parseJson(String(row.content_zh ?? ''), []), + contentEn: parseJson(String(row.content_en ?? ''), []), + image: row.image ? String(row.image) : null, + date: row.date ? String(row.date) : null, + readTime: Number(row.read_time) || 5, + author: String(row.author), + published: Number(row.published) || 0, + createdAt: String(row.created_at), + updatedAt: String(row.updated_at), + } +} + +function rowToWork(row: Record): Work { + return { + id: Number(row.id), + slug: String(row.slug), + category: row.category as Work['category'], + titleZh: String(row.title_zh), + titleEn: String(row.title_en), + descriptionZh: String(row.description_zh), + descriptionEn: String(row.description_en), + overviewZh: String(row.overview_zh), + overviewEn: String(row.overview_en), + challengeZh: String(row.challenge_zh), + challengeEn: String(row.challenge_en), + solutionZh: String(row.solution_zh), + solutionEn: String(row.solution_en), + clientZh: String(row.client_zh), + clientEn: String(row.client_en), + durationZh: String(row.duration_zh), + durationEn: String(row.duration_en), + year: String(row.year), + tags: parseJson(String(row.tags ?? ''), []), + image: row.image ? String(row.image) : null, + gallery: parseJson(String(row.gallery ?? ''), []), + url: row.url ? String(row.url) : null, + published: Number(row.published) || 0, + createdAt: String(row.created_at), + updatedAt: String(row.updated_at), + } +} + +const ARTICLE_COLS = `id, slug, category, title_zh, title_en, excerpt_zh, excerpt_en, content_zh, content_en, image, date, read_time, author, published, created_at, updated_at` +const WORK_COLS = `id, slug, category, title_zh, title_en, description_zh, description_en, overview_zh, overview_en, challenge_zh, challenge_en, solution_zh, solution_en, client_zh, client_en, duration_zh, duration_en, year, tags, image, gallery, url, published, created_at, updated_at` + +export function listArticles(options: { publishedOnly?: boolean } = {}): Article[] { + const { publishedOnly = true } = options + const sql = `SELECT ${ARTICLE_COLS} FROM articles + ${publishedOnly ? 'WHERE published = 1' : ''} + ORDER BY date DESC, id DESC` + const rows = getDb().prepare(sql).all() as Array> + return rows.map(rowToArticle) +} + +export function getArticleBySlug(slug: string, options: { publishedOnly?: boolean } = {}): Article | null { + const { publishedOnly = true } = options + const sql = `SELECT ${ARTICLE_COLS} FROM articles WHERE slug = ? ${publishedOnly ? 'AND published = 1' : ''}` + const row = getDb().prepare(sql).get(slug) as Record | undefined + return row ? rowToArticle(row) : null +} + +export function listWorks(options: { publishedOnly?: boolean } = {}): Work[] { + const { publishedOnly = true } = options + const sql = `SELECT ${WORK_COLS} FROM works + ${publishedOnly ? 'WHERE published = 1' : ''} + ORDER BY id ASC` + const rows = getDb().prepare(sql).all() as Array> + return rows.map(rowToWork) +} + +export function getWorkBySlug(slug: string, options: { publishedOnly?: boolean } = {}): Work | null { + const { publishedOnly = true } = options + const sql = `SELECT ${WORK_COLS} FROM works WHERE slug = ? ${publishedOnly ? 'AND published = 1' : ''}` + const row = getDb().prepare(sql).get(slug) as Record | undefined + return row ? rowToWork(row) : null +} + +/** 后台统计 */ +export function getContentStats(): { + articles: number + works: number + publishedArticles: number + publishedWorks: number +} { + const db = getDb() + const one = (sql: string) => (db.prepare(sql).get() as { c: number }).c + return { + articles: one('SELECT COUNT(*) AS c FROM articles'), + works: one('SELECT COUNT(*) AS c FROM works'), + publishedArticles: one('SELECT COUNT(*) AS c FROM articles WHERE published = 1'), + publishedWorks: one('SELECT COUNT(*) AS c FROM works WHERE published = 1'), + } +} diff --git a/server/utils/db.ts b/server/utils/db.ts index a6422c7..6f70923 100644 --- a/server/utils/db.ts +++ b/server/utils/db.ts @@ -1,7 +1,15 @@ import Database from 'better-sqlite3' import { mkdirSync } from 'node:fs' import { dirname } from 'node:path' +import { scryptSync, randomBytes } from 'node:crypto' import { getConfig } from './config' +import { articlesSeed, worksSeed } from './seed' + +/** 文章正文内容块 */ +export interface ArticleBlock { + type: 'paragraph' | 'heading' | 'quote' | 'image' + text: string +} /** * SQLite 数据层单例。 @@ -30,6 +38,7 @@ export function getDb(): Database.Database { _db.pragma('journal_mode = WAL') _db.pragma('foreign_keys = ON') migrate(_db) + seedIfEmpty(_db) return _db } @@ -89,9 +98,120 @@ function migrate(db: Database.Database): void { ); CREATE INDEX IF NOT EXISTS idx_comments_news ON comments(news_slug); + + -- 内容管理系统:动态(articles)与作品(works) + CREATE TABLE IF NOT EXISTS articles ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + slug TEXT NOT NULL UNIQUE, + category TEXT NOT NULL, + title_zh TEXT NOT NULL, + title_en TEXT NOT NULL, + excerpt_zh TEXT NOT NULL, + excerpt_en TEXT NOT NULL, + content_zh TEXT NOT NULL DEFAULT '[]', + content_en TEXT NOT NULL DEFAULT '[]', + image TEXT, + date TEXT, + read_time INTEGER NOT NULL DEFAULT 5, + author TEXT NOT NULL DEFAULT 'ArcticNewOne', + published INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE INDEX IF NOT EXISTS idx_articles_category ON articles(category); + CREATE INDEX IF NOT EXISTS idx_articles_published ON articles(published); + + CREATE TABLE IF NOT EXISTS works ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + slug TEXT NOT NULL UNIQUE, + category TEXT NOT NULL, + title_zh TEXT NOT NULL, + title_en TEXT NOT NULL, + description_zh TEXT NOT NULL, + description_en TEXT NOT NULL, + overview_zh TEXT NOT NULL DEFAULT '', + overview_en TEXT NOT NULL DEFAULT '', + challenge_zh TEXT NOT NULL DEFAULT '', + challenge_en TEXT NOT NULL DEFAULT '', + solution_zh TEXT NOT NULL DEFAULT '', + solution_en TEXT NOT NULL DEFAULT '', + client_zh TEXT NOT NULL DEFAULT '', + client_en TEXT NOT NULL DEFAULT '', + duration_zh TEXT NOT NULL DEFAULT '', + duration_en TEXT NOT NULL DEFAULT '', + year TEXT NOT NULL DEFAULT '', + tags TEXT NOT NULL DEFAULT '[]', + image TEXT, + gallery TEXT NOT NULL DEFAULT '[]', + url TEXT, + published INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE INDEX IF NOT EXISTS idx_works_category ON works(category); + CREATE INDEX IF NOT EXISTS idx_works_published ON works(published); `) } +/** + * 初始化种子数据:内容表为空时灌入 articles/works 种子; + * users 为空且配置了 adminInitialPassword 时创建预置管理员。 + */ +function seedIfEmpty(db: Database.Database): void { + const { adminInitialPassword, adminEmails } = getConfig() + + const articleCount = (db.prepare('SELECT COUNT(*) AS c FROM articles').get() as { c: number }).c + if (articleCount === 0) { + const insert = db.prepare( + `INSERT INTO articles + (slug, category, title_zh, title_en, excerpt_zh, excerpt_en, content_zh, content_en, image, date, read_time, author, published) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + const tx = db.transaction(() => { + for (const a of articlesSeed) { + insert.run(a.slug, a.category, a.titleZh, a.titleEn, a.excerptZh, a.excerptEn, + JSON.stringify(a.contentZh), JSON.stringify(a.contentEn), a.image, a.date, a.readTime, a.author, a.published) + } + }) + tx() + } + + const workCount = (db.prepare('SELECT COUNT(*) AS c FROM works').get() as { c: number }).c + if (workCount === 0) { + const insert = db.prepare( + `INSERT INTO works + (slug, category, title_zh, title_en, description_zh, description_en, + overview_zh, overview_en, challenge_zh, challenge_en, solution_zh, solution_en, + client_zh, client_en, duration_zh, duration_en, year, tags, image, gallery, url, published) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + const tx = db.transaction(() => { + for (const w of worksSeed) { + insert.run(w.slug, w.category, w.titleZh, w.titleEn, w.descriptionZh, w.descriptionEn, + w.overviewZh, w.overviewEn, w.challengeZh, w.challengeEn, w.solutionZh, w.solutionEn, + w.clientZh, w.clientEn, w.durationZh, w.durationEn, w.year, + JSON.stringify(w.tags), w.image, JSON.stringify(w.gallery), w.url, w.published) + } + }) + tx() + } + + // 预置管理员(仅当首次初始化且配置了初始密码) + const userCount = (db.prepare('SELECT COUNT(*) AS c FROM users').get() as { c: number }).c + if (userCount === 0 && adminInitialPassword && adminEmails.length > 0) { + const email = adminEmails[0] + const username = 'admin' + // 与 auth.ts 相同的 salt:hash 存储格式(scrypt) + const salt = randomBytes(16).toString('hex') + const hash = scryptSync(adminInitialPassword, salt, 64).toString('hex') + db.prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)') + .run(username, email, `${salt}:${hash}`, 'admin') + console.log('[seed] 已创建预置管理员账号: admin(邮箱 ' + email + ')') + } +} + /** 供服务端任意位置安全关闭数据库(测试/热更新用) */ export function closeDb(): void { if (_db) { diff --git a/server/utils/seed.ts b/server/utils/seed.ts new file mode 100644 index 0000000..73421f8 --- /dev/null +++ b/server/utils/seed.ts @@ -0,0 +1,737 @@ +/** + * 种子数据(由 scripts/generate-seed.mjs 生成,勿手改)。 + * 站点初始内容:6 篇动态 + 6 个作品(中英双语)。 + * DB 初始化(migrate)时若对应表为空则自动灌入。 + */ +import type { ArticleBlock } from './db' + +export interface ArticleSeed { + slug: string + category: 'insights' | 'projects' | 'announcements' + titleZh: string + titleEn: string + excerptZh: string + excerptEn: string + contentZh: ArticleBlock[] + contentEn: ArticleBlock[] + image: string + date: string + readTime: number + author: string + published: number +} + +export interface WorkSeed { + slug: string + category: 'webDesign' | 'branding' | 'development' + titleZh: string + titleEn: string + descriptionZh: string + descriptionEn: string + overviewZh: string + overviewEn: string + challengeZh: string + challengeEn: string + solutionZh: string + solutionEn: string + clientZh: string + clientEn: string + durationZh: string + durationEn: string + year: string + tags: string[] + image: string + gallery: string[] + url: string | null + published: number +} + +export const articlesSeed: ArticleSeed[] = [ + { + "slug": "design-trends-2026", + "category": "insights", + "titleZh": "2026 年设计趋势展望", + "titleEn": "Design Trends Shaping 2026", + "excerptZh": "从极简主义的回归到大胆排版的兴起,从 3D 元素普及到 AI 辅助设计成熟,探索塑造今年数字体验的前沿趋势。", + "excerptEn": "Explore the emerging design trends defining digital experiences this year, from minimalism to bold typography.", + "contentZh": [ + { + "type": "paragraph", + "text": "2026 年,设计行业正在经历一场深刻的变革。从极简主义的回归到大胆排版的兴起,从 3D 元素的普及到 AI 辅助设计的成熟,这些趋势正在重新定义数字体验的边界。作为设计从业者,我们需要紧跟这些变化,才能为客户创造更具竞争力的作品。" + }, + { + "type": "heading", + "text": "极简主义的回归" + }, + { + "type": "paragraph", + "text": "在信息过载的时代,用户越来越渴望简洁、清晰的界面。2026 年的极简主义不再是简单的「少即是多」,而是通过精心的信息架构和视觉层次,在有限的空间内传达更多价值。留白不再是空白,而是一种有意为之的设计语言。" + }, + { + "type": "quote", + "text": "好的设计不是添加更多,而是去除不必要的。在 2026 年,这一点比以往任何时候都更加重要。" + }, + { + "type": "heading", + "text": "大胆排版与动态文字" + }, + { + "type": "paragraph", + "text": "排版正在从配角变成主角。大尺寸、高对比度的字体设计正在成为品牌表达的重要手段。动态文字效果的普及,让排版不再是静态的装饰,而是能够与用户互动的活元素。" + }, + { + "type": "heading", + "text": "AI 辅助设计的成熟" + }, + { + "type": "paragraph", + "text": "AI 工具正在从「替代设计师」转向「增强设计师」。智能布局建议、自动化配色方案、实时设计反馈等功能,让设计师能够专注于创意和策略,而非重复性的执行工作。" + } + ], + "contentEn": [ + { + "type": "paragraph", + "text": "In 2026, the design industry is undergoing a profound transformation. From the return of minimalism to the rise of bold typography, from the普及 of 3D elements to the maturity of AI-assisted design, these trends are redefining the boundaries of digital experiences." + }, + { + "type": "heading", + "text": "The Return of Minimalism" + }, + { + "type": "paragraph", + "text": "In an age of information overload, users increasingly渴望 clean, clear interfaces. 2026's minimalism isn't just 'less is more' — it's about delivering more value in limited space through careful information architecture and visual hierarchy." + }, + { + "type": "quote", + "text": "Good design isn't about adding more, it's about removing the unnecessary. In 2026, this matters more than ever." + }, + { + "type": "heading", + "text": "Bold Typography & Dynamic Text" + }, + { + "type": "paragraph", + "text": "Typography is moving from supporting actor to leading role. Large, high-contrast font designs are becoming important brand expression tools. Dynamic text effects are making typography a living, interactive element rather than static decoration." + }, + { + "type": "heading", + "text": "Maturity of AI-Assisted Design" + }, + { + "type": "paragraph", + "text": "AI tools are shifting from 'replacing designers' to 'empowering designers.' Smart layout suggestions, automated color schemes, and real-time design feedback let designers focus on creativity and strategy rather than repetitive execution." + } + ], + "image": "https://picsum.photos/id/1/800/500", + "date": "2026-05-28", + "readTime": 5, + "author": "ArcticNewOne", + "published": 1 + }, + { + "slug": "forma-digital-launch", + "category": "projects", + "titleZh": "Forma Digital 电商平台正式上线", + "titleEn": "Forma Digital Platform Launch", + "excerptZh": "我们很高兴地宣布 Forma Digital 电商平台正式上线,上线后转化率提升 45%。", + "excerptEn": "We are excited to announce the successful launch of Forma Digital, a revolutionary e-commerce experience.", + "contentZh": [ + { + "type": "paragraph", + "text": "经过三个月的精心打造,我们很高兴地宣布 Forma Digital 电商平台正式上线!这个项目是我们团队迄今为止最具挑战性的作品之一,也是我们技术实力和设计能力的集中体现。" + }, + { + "type": "heading", + "text": "项目背景" + }, + { + "type": "paragraph", + "text": "Forma Digital 是一家专注于高端家居用品的电商品牌。他们需要一个能够完美展示产品质感、提供流畅购物体验的平台。原有的网站存在加载缓慢、移动端体验差、转化率低等问题。" + }, + { + "type": "quote", + "text": "北极新一团队不仅理解我们的需求,更超越了我们的期望。新平台上线后,我们的转化率提升了 45%。" + }, + { + "type": "heading", + "text": "技术亮点" + }, + { + "type": "paragraph", + "text": "我们采用了 React + Next.js 技术栈,实现了服务端渲染和静态生成。通过图片懒加载、代码分割、CDN 加速等技术手段,将首屏加载时间从 4.5 秒降低到 1.2 秒。" + }, + { + "type": "heading", + "text": "成果展示" + }, + { + "type": "paragraph", + "text": "新平台上线后,用户停留时间增加了 60%,跳出率降低了 35%,转化率提升了 45%。客户对新平台的设计和性能都非常满意。" + } + ], + "contentEn": [ + { + "type": "paragraph", + "text": "After three months of careful crafting, we're excited to announce the official launch of the Forma Digital e-commerce platform! This project is one of our team's most challenging works to date." + }, + { + "type": "heading", + "text": "Project Background" + }, + { + "type": "paragraph", + "text": "Forma Digital is an e-commerce brand focusing on premium home goods. They needed a platform that could perfectly showcase product quality while delivering a smooth shopping experience." + }, + { + "type": "quote", + "text": "The ArcticNewOne team not only understood our needs but exceeded our expectations. After the new platform launched, our conversion rate increased by 45%." + }, + { + "type": "heading", + "text": "Technical Highlights" + }, + { + "type": "paragraph", + "text": "We used React + Next.js for server-side rendering and static generation. Through lazy loading, code splitting, and CDN acceleration, we reduced first load time from 4.5s to 1.2s." + }, + { + "type": "heading", + "text": "Results" + }, + { + "type": "paragraph", + "text": "After launch, user停留 time increased by 60%, bounce rate decreased by 35%, and conversion rate improved by 45%." + } + ], + "image": "https://picsum.photos/id/201/800/500", + "date": "2026-05-15", + "readTime": 3, + "author": "ArcticNewOne", + "published": 1 + }, + { + "slug": "studio-expansion", + "category": "announcements", + "titleZh": "工作室扩张公告", + "titleEn": "Studio Expansion Announcement", + "excerptZh": "ArcticNewOne 正在成长!我们正在扩展团队与服务能力,以更好地服务客户。", + "excerptEn": "ArcticNewOne is growing! We are expanding our team and capabilities to serve you better.", + "contentZh": [ + { + "type": "paragraph", + "text": "随着业务的持续增长和客户需求的不断增加,我们很高兴地宣布 ArcticNewOne 工作室正式扩展!我们将增加新的团队成员,拓展服务能力,为客户提供更优质的数字化解决方案。" + }, + { + "type": "heading", + "text": "团队扩展" + }, + { + "type": "paragraph", + "text": "我们将新增 5 名资深设计师和 3 名高级开发工程师,覆盖前端、后端、UI/UX 等多个领域。这些新成员都拥有丰富的行业经验,曾服务于多家知名企业。" + }, + { + "type": "quote", + "text": "人才是我们最宝贵的资产。通过扩展团队,我们能够承接更多项目,同时保持一贯的高品质交付。" + }, + { + "type": "heading", + "text": "服务升级" + }, + { + "type": "paragraph", + "text": "除了现有的网页设计、品牌设计、程序开发等服务,我们还将新增数据可视化、AI 应用开发、AR/VR 体验设计等前沿服务。" + }, + { + "type": "heading", + "text": "展望未来" + }, + { + "type": "paragraph", + "text": "我们计划在未来一年内完成 50+ 项目,服务 30+ 新客户。同时,我们将继续深耕技术创新,探索更多可能性,为客户创造更大价值。" + } + ], + "contentEn": [ + { + "type": "paragraph", + "text": "With continued business growth and increasing client demand, we're excited to announce the official expansion of ArcticNewOne Studio!" + }, + { + "type": "heading", + "text": "Team Growth" + }, + { + "type": "paragraph", + "text": "We're adding 5 senior designers and 3 senior developers covering frontend, backend, UI/UX, and more. All new members have extensive industry experience." + }, + { + "type": "quote", + "text": "Talent is our most valuable asset. By expanding our team, we can take on more projects while maintaining consistent high-quality delivery." + }, + { + "type": "heading", + "text": "Service Upgrade" + }, + { + "type": "paragraph", + "text": "In addition to existing services, we're adding data visualization, AI application development, AR/VR experience design, and other cutting-edge services." + }, + { + "type": "heading", + "text": "Looking Ahead" + }, + { + "type": "paragraph", + "text": "We plan to complete 50+ projects and serve 30+ new clients in the coming year while continuing to explore new possibilities." + } + ], + "image": "https://picsum.photos/id/164/800/500", + "date": "2026-05-10", + "readTime": 2, + "author": "ArcticNewOne", + "published": 1 + }, + { + "slug": "ux-research-methods", + "category": "insights", + "titleZh": "现代 UX 研究方法", + "titleEn": "Modern UX Research Methods", + "excerptZh": "深入解析影响我们设计决策的最新用户体验研究方法,从远程测试到行为数据分析。", + "excerptEn": "Dive into the latest user experience research methodologies, from remote testing to behavioral analytics.", + "contentZh": [ + { + "type": "paragraph", + "text": "用户体验研究是设计决策的基础。在 2026 年,随着技术的发展和用户行为的变化,UX 研究方法也在不断演进。本文将介绍几种最有效的现代 UX 研究方法。" + }, + { + "type": "heading", + "text": "远程用户测试" + }, + { + "type": "paragraph", + "text": "远程用户测试已经成为 UX 研究的主流方法。通过专业的远程测试平台,我们可以在短时间内招募到全球各地的测试用户,获取更广泛的反馈。" + }, + { + "type": "quote", + "text": "远程测试不仅降低了成本,更重要的是让我们能够接触到更真实的用户场景。" + }, + { + "type": "heading", + "text": "行为数据分析" + }, + { + "type": "paragraph", + "text": "通过热力图、滚动深度、点击流等行为数据,我们可以客观地了解用户如何与产品互动。这些数据弥补了传统访谈和问卷的不足,提供了更真实的用户行为洞察。" + }, + { + "type": "heading", + "text": "AI 辅助分析" + }, + { + "type": "paragraph", + "text": "AI 工具正在帮助我们更高效地分析用户反馈。情感分析、主题聚类、趋势预测等功能,让我们能够从海量数据中快速提取有价值的洞察。" + } + ], + "contentEn": [ + { + "type": "paragraph", + "text": "UX research is the foundation of design decisions. In 2026, as technology evolves and user behaviors change, UX research methods continue to advance." + }, + { + "type": "heading", + "text": "Remote User Testing" + }, + { + "type": "paragraph", + "text": "Remote user testing has become mainstream. Through professional platforms, we can recruit test users globally and gather broader feedback in less time." + }, + { + "type": "quote", + "text": "Remote testing not only reduces costs but more importantly lets us access more authentic user scenarios." + }, + { + "type": "heading", + "text": "Behavioral Data Analysis" + }, + { + "type": "paragraph", + "text": "Through heatmaps, scroll depth, click streams, and other behavioral data, we can objectively understand how users interact with products." + }, + { + "type": "heading", + "text": "AI-Assisted Analysis" + }, + { + "type": "paragraph", + "text": "AI tools help us analyze user feedback more efficiently. Sentiment analysis, topic clustering, and trend prediction help extract valuable insights from massive data." + } + ], + "image": "https://picsum.photos/id/180/800/500", + "date": "2026-04-28", + "readTime": 7, + "author": "ArcticNewOne", + "published": 1 + }, + { + "slug": "bold-moves-case-study", + "category": "projects", + "titleZh": "Bold Moves:项目复盘", + "titleEn": "Bold Moves: A Case Study", + "excerptZh": "走进我们屡获殊荣的建筑可视化项目幕后,见证前沿 3D 技术如何重塑用户体验。", + "excerptEn": "Behind the scenes of our award-winning architectural visualization project featuring cutting-edge 3D technology.", + "contentZh": [ + { + "type": "paragraph", + "text": "Bold Moves 是一个展示创新建筑设计的交互式网站项目。本文将深入介绍这个项目的设计思路、技术实现和最终成果。" + }, + { + "type": "heading", + "text": "设计理念" + }, + { + "type": "paragraph", + "text": "Bold Moves 希望通过数字方式展示建筑设计的魅力。我们决定采用 3D 可视化技术,让用户能够从任意角度欣赏建筑细节,获得沉浸式的体验。" + }, + { + "type": "quote", + "text": "我们想要的不只是一个展示网站,而是一个能够让用户「走进」建筑的数字空间。" + }, + { + "type": "heading", + "text": "技术挑战" + }, + { + "type": "paragraph", + "text": "高质量的 3D 渲染需要强大的计算能力,而网页端的性能有限。我们通过模型优化、LOD 技术、WebGL 渲染等手段,在保证视觉质量的同时,实现了流畅的交互体验。" + }, + { + "type": "heading", + "text": "最终成果" + }, + { + "type": "paragraph", + "text": "项目上线后获得了广泛好评,赢得了多个设计奖项。用户平均停留时间超过 5 分钟,远高于行业平均水平。" + } + ], + "contentEn": [ + { + "type": "paragraph", + "text": "Bold Moves is an interactive website showcasing innovative architectural designs. This article provides an in-depth look at the design思路, technical implementation, and final results." + }, + { + "type": "heading", + "text": "Design Philosophy" + }, + { + "type": "paragraph", + "text": "Bold Moves wanted to showcase architectural beauty digitally. We decided to use 3D visualization to let users appreciate architectural details from any angle." + }, + { + "type": "quote", + "text": "We didn't just want a showcase website — we wanted a digital space where users could 'walk into' the architecture." + }, + { + "type": "heading", + "text": "Technical Challenges" + }, + { + "type": "paragraph", + "text": "High-quality 3D rendering requires significant computing power, but web performance is limited. We achieved smooth interactions through model optimization, LOD techniques, and WebGL rendering." + }, + { + "type": "heading", + "text": "Final Results" + }, + { + "type": "paragraph", + "text": "The project received widespread acclaim and won multiple design awards. Average user停留 time exceeded 5 minutes, well above industry average." + } + ], + "image": "https://picsum.photos/id/119/800/500", + "date": "2026-04-20", + "readTime": 6, + "author": "ArcticNewOne", + "published": 1 + }, + { + "slug": "new-tools-integration", + "category": "announcements", + "titleZh": "工具箱新增多款实用工具", + "titleEn": "New Tools Added to Our Platform", + "excerptZh": "看看我们工具箱的最新成员,覆盖设计、开发、协作,助你精简工作流、提升生产力。", + "excerptEn": "Check out the latest additions to our toolbox across design, development and collaboration.", + "contentZh": [ + { + "type": "paragraph", + "text": "为了更好地服务客户,我们不断扩充和完善我们的工具箱。最近,我们新增了多款实用工具,涵盖设计、开发、协作等多个领域。" + }, + { + "type": "heading", + "text": "设计工具升级" + }, + { + "type": "paragraph", + "text": "我们引入了最新的设计协作平台,支持实时多人编辑、版本管理、设计系统集成等功能。设计师和开发者可以在同一个平台上无缝协作。" + }, + { + "type": "quote", + "text": "工欲善其事,必先利其器。好的工具能够大幅提升团队效率。" + }, + { + "type": "heading", + "text": "开发工具增强" + }, + { + "type": "paragraph", + "text": "新增了自动化测试框架、性能监控工具、代码质量检查等开发工具。这些工具帮助我们在开发过程中及时发现和解决问题,保证代码质量。" + }, + { + "type": "heading", + "text": "协作工具优化" + }, + { + "type": "paragraph", + "text": "我们升级了项目管理平台,新增了看板视图、时间追踪、资源分配等功能。项目经理可以更直观地掌控项目进度,团队成员可以更高效地协作。" + } + ], + "contentEn": [ + { + "type": "paragraph", + "text": "To better serve our clients, we continuously expand and improve our toolbox. Recently, we've added several practical tools covering design, development, collaboration, and more." + }, + { + "type": "heading", + "text": "Design Tool Upgrades" + }, + { + "type": "paragraph", + "text": "We've引入 the latest design collaboration platform supporting real-time multi-person editing, version management, and design system integration." + }, + { + "type": "quote", + "text": "Good tools significantly boost team efficiency. The right toolchain is key to delivering quality work." + }, + { + "type": "heading", + "text": "Development Tool Enhancements" + }, + { + "type": "paragraph", + "text": "Added automated testing frameworks, performance monitoring tools, and code quality checks to help identify and resolve issues during development." + }, + { + "type": "heading", + "text": "Collaboration Tool Optimization" + }, + { + "type": "paragraph", + "text": "We upgraded our project management platform with new Kanban views, time tracking, and resource allocation features for better project oversight." + } + ], + "image": "https://picsum.photos/id/326/800/500", + "date": "2026-04-12", + "readTime": 4, + "author": "ArcticNewOne", + "published": 1 + } +] + +export const worksSeed: WorkSeed[] = [ + { + "slug": "forma-digital", + "category": "webDesign", + "titleZh": "Forma Digital", + "titleEn": "Forma Digital", + "descriptionZh": "现代化的电商平台,无缝用户体验与动态产品展示。", + "descriptionEn": "A modern e-commerce platform with seamless user experience and dynamic product showcases.", + "overviewZh": "Forma Digital 是一个现代化的电商平台,致力于为用户提供无缝的购物体验。我们重新设计了整个用户界面,采用极简主义设计风格,突出产品展示,提升转化率。", + "overviewEn": "Forma Digital is a modern e-commerce platform designed to provide a seamless shopping experience. We redesigned the entire user interface with a minimalist design approach, focusing on product showcase and conversion optimization.", + "challengeZh": "客户需要一个既能展示高端产品,又能提供流畅购物体验的平台。原有的网站加载缓慢,用户体验差,转化率低下。", + "challengeEn": "The client needed a platform that could both showcase premium products and deliver a smooth shopping experience. The existing website was slow, had poor mobile experience, and low conversion rates.", + "solutionZh": "我们采用了 React + Next.js 技术栈,实现了服务端渲染和静态生成,大幅提升加载速度。同时重新设计了产品展示页面,采用沉浸式大图展示,配合流畅的动画过渡。", + "solutionEn": "We built the platform with React + Next.js, implementing server-side rendering and static generation for blazing fast load times. The product pages feature immersive large-format imagery with smooth animation transitions.", + "clientZh": "Forma Digital Inc.", + "clientEn": "Forma Digital Inc.", + "durationZh": "3 个月", + "durationEn": "3 months", + "year": "2026", + "tags": [ + "Web Design", + "E-commerce", + "React" + ], + "image": "https://picsum.photos/id/201/1200/800", + "gallery": [ + "https://picsum.photos/id/201/800/600", + "https://picsum.photos/id/202/800/600", + "https://picsum.photos/id/203/800/600", + "https://picsum.photos/id/204/800/600" + ], + "url": null, + "published": 1 + }, + { + "slug": "one-step", + "category": "branding", + "titleZh": "One Step", + "titleEn": "One Step", + "descriptionZh": "为健身应用打造的品牌形象与营销战役,聚焦可持续习惯养成。", + "descriptionEn": "Brand identity and marketing campaign for a fitness app focused on sustainable habits.", + "overviewZh": "One Step 是一款专注于健康习惯养成的健身应用。我们为其打造了完整的品牌视觉识别系统,包括 Logo 设计、UI 界面和营销物料。", + "overviewEn": "One Step is a fitness app focused on building healthy habits. We created a complete brand visual identity system including logo design, UI interface, and marketing materials.", + "challengeZh": "在竞争激烈的健身应用市场中,如何通过品牌设计脱颖而出,建立独特的品牌认知。", + "challengeEn": "In the competitive fitness app market, how to stand out through brand design and establish unique brand recognition.", + "solutionZh": "我们以「一步一个脚印」为核心理念,设计了简洁有力的品牌标识。采用渐变色彩和圆润的图形语言,传达健康、积极、向上的品牌调性。", + "solutionEn": "With the core concept of 'one step at a time', we designed a clean and powerful brand identity. Using gradient colors and rounded graphic language to convey health, positivity, and progress.", + "clientZh": "One Step Fitness", + "clientEn": "One Step Fitness", + "durationZh": "2 个月", + "durationEn": "2 months", + "year": "2024", + "tags": [ + "Branding", + "Marketing", + "UI/UX" + ], + "image": "https://picsum.photos/id/180/1200/800", + "gallery": [ + "https://picsum.photos/id/180/800/600", + "https://picsum.photos/id/181/800/600", + "https://picsum.photos/id/182/800/600", + "https://picsum.photos/id/183/800/600" + ], + "url": null, + "published": 1 + }, + { + "slug": "nero-vision", + "category": "development", + "titleZh": "Nero Vision", + "titleEn": "Nero Vision", + "descriptionZh": "面向创意专业人士的全栈作品集管理应用。", + "descriptionEn": "Full-stack web application for creative professionals to manage their portfolios.", + "overviewZh": "Nero Vision 是一个面向创意专业人士的作品集管理平台,帮助设计师和艺术家展示和管理他们的创作。", + "overviewEn": "Nero Vision is a portfolio management platform for creative professionals, helping designers and artists showcase and manage their work.", + "challengeZh": "创意人士需要一个既能完美展示作品,又能方便管理的平台。现有解决方案要么太复杂,要么展示效果不佳。", + "challengeEn": "Creative professionals need a platform that can perfectly showcase work while being easy to manage. Existing solutions are either too complex or have poor display quality.", + "solutionZh": "我们采用 Vue.js + Node.js 全栈开发,设计了直观的拖拽式作品管理界面,配合精美的展示模板,让创意人士轻松打造个人品牌。", + "solutionEn": "We developed a full-stack application with Vue.js + Node.js, designing an intuitive drag-and-drop portfolio management interface with beautiful display templates.", + "clientZh": "Nero Studio", + "clientEn": "Nero Studio", + "durationZh": "4 个月", + "durationEn": "4 months", + "year": "2025", + "tags": [ + "Development", + "Vue.js", + "Node.js" + ], + "image": "https://picsum.photos/id/119/1200/800", + "gallery": [ + "https://picsum.photos/id/119/800/600", + "https://picsum.photos/id/120/800/600", + "https://picsum.photos/id/121/800/600", + "https://picsum.photos/id/122/800/600" + ], + "url": null, + "published": 1 + }, + { + "slug": "bold-moves", + "category": "webDesign", + "titleZh": "Bold Moves", + "titleEn": "Bold Moves", + "descriptionZh": "以 3D 可视化展示创新建筑设计的交互式网站。", + "descriptionEn": "Interactive website showcasing innovative architectural designs with 3D visualizations.", + "overviewZh": "Bold Moves 是一个展示创新建筑设计的交互式网站,通过 3D 可视化技术,让用户身临其境地体验建筑之美。", + "overviewEn": "Bold Moves is an interactive website showcasing innovative architectural designs through 3D visualization technology, letting users experience architecture immersively.", + "challengeZh": "如何将复杂的建筑设计以直观、吸引人的方式展示给普通用户,同时保持专业性。", + "challengeEn": "How to present complex architectural designs in an intuitive and engaging way to general users while maintaining professionalism.", + "solutionZh": "我们使用 Three.js 实现了高质量的 3D 渲染,配合流畅的交互设计,用户可以从任意角度欣赏建筑细节。同时加入了光影效果和材质展示,提升视觉冲击力。", + "solutionEn": "We used Three.js for high-quality 3D rendering with smooth interactive design, allowing users to appreciate architectural details from any angle, with lighting effects and material displays.", + "clientZh": "Bold Moves Architecture", + "clientEn": "Bold Moves Architecture", + "durationZh": "5 个月", + "durationEn": "5 months", + "year": "2024", + "tags": [ + "Web Design", + "3D", + "Three.js" + ], + "image": "https://picsum.photos/id/164/1200/800", + "gallery": [ + "https://picsum.photos/id/164/800/600", + "https://picsum.photos/id/165/800/600", + "https://picsum.photos/id/166/800/600", + "https://picsum.photos/id/167/800/600" + ], + "url": null, + "published": 1 + }, + { + "slug": "echo-labs", + "category": "branding", + "titleZh": "Echo Labs", + "titleEn": "Echo Labs", + "descriptionZh": "AI 科技创业公司的企业品牌与视觉识别。", + "descriptionEn": "Corporate branding and visual identity for a tech startup in the AI space.", + "overviewZh": "Echo Labs 是一家 AI 领域的科技创业公司,我们为其打造了完整的品牌视觉识别系统和企业官网。", + "overviewEn": "Echo Labs is an AI tech startup. We created a complete brand visual identity system and corporate website for them.", + "challengeZh": "AI 领域的品牌需要既体现科技感,又要有人文温度,避免过于冷冰冰的技术感。", + "challengeEn": "AI brands need to convey both technology and humanity, avoiding being too cold or technical.", + "solutionZh": "我们以「回声」为概念,设计了富有动感的品牌标识。采用深色主题配合渐变色彩,营造科技感的同时,通过圆润的图形语言增添亲和力。", + "solutionEn": "With the concept of 'echo', we designed a dynamic brand identity. Using dark themes with gradient colors for a tech feel, while rounded graphic language adds approachability.", + "clientZh": "Echo Labs AI", + "clientEn": "Echo Labs AI", + "durationZh": "3 个月", + "durationEn": "3 months", + "year": "2025", + "tags": [ + "Branding", + "Visual Identity", + "Corporate" + ], + "image": "https://picsum.photos/id/101/1200/800", + "gallery": [ + "https://picsum.photos/id/101/800/600", + "https://picsum.photos/id/102/800/600", + "https://picsum.photos/id/103/800/600", + "https://picsum.photos/id/104/800/600" + ], + "url": null, + "published": 1 + }, + { + "slug": "flux-api", + "category": "development", + "titleZh": "Flux API", + "titleEn": "Flux API", + "descriptionZh": "具备完善文档与开发者工具的可扩展 REST API 服务。", + "descriptionEn": "Scalable REST API with comprehensive documentation and developer tools.", + "overviewZh": "Flux API 是一个可扩展的 REST API 服务平台,提供全面的文档和开发者工具,帮助开发者快速集成。", + "overviewEn": "Flux API is a scalable REST API service platform with comprehensive documentation and developer tools to help developers integrate quickly.", + "challengeZh": "API 文档和开发者体验是技术产品的核心竞争力,如何让复杂的 API 变得易于理解和使用。", + "challengeEn": "API documentation and developer experience are core competitive advantages. How to make complex APIs easy to understand and use.", + "solutionZh": "我们设计了交互式 API 文档,支持在线测试和代码生成。同时提供了多语言 SDK 和详细的教程,大幅降低开发者的学习成本。", + "solutionEn": "We designed interactive API documentation with online testing and code generation. Multi-language SDKs and detailed tutorials significantly reduce the learning curve for developers.", + "clientZh": "Flux Technologies", + "clientEn": "Flux Technologies", + "durationZh": "6 个月", + "durationEn": "6 months", + "year": "2025", + "tags": [ + "Development", + "API", + "Python" + ], + "image": "https://picsum.photos/id/326/1200/800", + "gallery": [ + "https://picsum.photos/id/326/800/600", + "https://picsum.photos/id/327/800/600", + "https://picsum.photos/id/328/800/600", + "https://picsum.photos/id/329/800/600" + ], + "url": null, + "published": 1 + } +] diff --git a/server/utils/validateContent.ts b/server/utils/validateContent.ts new file mode 100644 index 0000000..d62b8b2 --- /dev/null +++ b/server/utils/validateContent.ts @@ -0,0 +1,49 @@ +import type { ArticleBlock } from './db' + +/** + * 后台内容校验/归一化(articles / works 的 post/patch 共用)。 + */ + +export const ARTICLE_CATEGORIES = ['insights', 'projects', 'announcements'] +export const WORK_CATEGORIES = ['webDesign', 'branding', 'development'] +export const BLOCK_TYPES = ['paragraph', 'heading', 'quote', 'image'] + +export function normalizeSlug(value: unknown): string { + return String(value ?? '').trim() +} + +export function isValidSlug(slug: string): boolean { + return /^[a-z0-9-]{2,64}$/.test(slug) +} + +export function isValidArticleCategory(value: unknown): boolean { + return typeof value === 'string' && ARTICLE_CATEGORIES.includes(value) +} + +export function isValidWorkCategory(value: unknown): boolean { + return typeof value === 'string' && WORK_CATEGORIES.includes(value) +} + +/** 归一化内容块数组(过滤非法块) */ +export function normalizeBlocks(value: unknown): ArticleBlock[] { + if (!Array.isArray(value)) return [] + return value + .filter( + (b): b is ArticleBlock => + !!b && + typeof b === 'object' && + BLOCK_TYPES.includes((b as ArticleBlock).type) && + typeof (b as ArticleBlock).text === 'string', + ) + .map((b) => ({ type: b.type, text: b.text.slice(0, 20000) })) +} + +export function normalizeTags(value: unknown): string[] { + if (!Array.isArray(value)) return [] + return value.filter((t): t is string => typeof t === 'string' && t.trim()).map((t) => t.trim()).slice(0, 20) +} + +export function normalizeGallery(value: unknown): string[] { + if (!Array.isArray(value)) return [] + return value.filter((u): u is string => typeof u === 'string' && u.trim()).map((u) => u.trim()).slice(0, 20) +} From 685c7b51d19839b59eabb4cdde1585a04d562182 Mon Sep 17 00:00:00 2001 From: chenchun Date: Thu, 6 Aug 2026 17:26:26 +0800 Subject: [PATCH 03/12] =?UTF-8?q?feat:=20=E6=94=B6=E5=AE=98=E8=A1=A5?= =?UTF-8?q?=E9=BD=90=E5=85=A8=E9=83=A8=E6=9C=AA=E5=AE=9E=E7=8E=B0=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 账号体系:修改密码(/account + PATCH /api/auth/password)、自助删除账号 (DELETE /api/auth/me)、订阅退订(token + /unsubscribe 页) - 前台/SEO:RSS 订阅 /feed.xml、作品详情分享、canonical URL、 文章 Article JSON-LD、品牌化错误页(i18n) - 后台增强:图片管理 /admin/uploads、操作审计日志 /admin/audit(含清空)、 联系消息已读标记、评论列表分页 - 工程:vitest 测试(密码哈希/内容校验器/种子完整性,12 例)+ pnpm test - DB 迁移:contacts.read、subscribers.token、audit_logs(老库 ALTER 兼容) - 密码逻辑抽为 server/utils/password.ts 供测试 --- app/app.vue | 9 +- app/components/admin/AdminSidebar.vue | 4 +- app/error.vue | 27 +-- app/pages/account.vue | 132 ++++++++++++ app/pages/admin/audit.vue | 227 ++++++++++++++++++++ app/pages/admin/comments.vue | 43 +++- app/pages/admin/contacts.vue | 36 ++++ app/pages/admin/uploads.vue | 165 ++++++++++++++ app/pages/news/[slug].vue | 26 ++- app/pages/unsubscribe.vue | 82 +++++++ app/pages/work/[slug].vue | 61 +++++- i18n/locales/en.json | 41 +++- i18n/locales/zh.json | 41 +++- package.json | 6 +- pnpm-lock.yaml | 218 ++++++++++++++++++- server/api/admin/articles.post.ts | 3 + server/api/admin/articles/[id].delete.ts | 4 +- server/api/admin/articles/[id].patch.ts | 4 +- server/api/admin/audit.delete.ts | 13 ++ server/api/admin/audit.get.ts | 24 +++ server/api/admin/comments.get.ts | 18 +- server/api/admin/comments/[id].delete.ts | 4 +- server/api/admin/contacts.get.ts | 2 +- server/api/admin/contacts/[id].delete.ts | 4 +- server/api/admin/contacts/[id].patch.ts | 25 +++ server/api/admin/subscribers/[id].delete.ts | 4 +- server/api/admin/upload.post.ts | 4 +- server/api/admin/uploads.get.ts | 27 +++ server/api/admin/uploads/[name].delete.ts | 28 +++ server/api/admin/users/[id].delete.ts | 4 +- server/api/admin/users/[id].patch.ts | 4 +- server/api/admin/works.post.ts | 4 +- server/api/admin/works/[id].delete.ts | 4 +- server/api/admin/works/[id].patch.ts | 4 +- server/api/auth/me.delete.ts | 23 ++ server/api/auth/password.patch.ts | 28 +++ server/api/newsletter.post.ts | 13 +- server/api/newsletter/unsubscribe.post.ts | 24 +++ server/routes/feed.xml.ts | 51 +++++ server/utils/audit.ts | 18 ++ server/utils/auth.ts | 26 +-- server/utils/db.ts | 27 +++ server/utils/password.ts | 26 +++ tests/password.test.ts | 26 +++ tests/seed.test.ts | 45 ++++ tests/validateContent.test.ts | 55 +++++ vitest.config.ts | 8 + 47 files changed, 1600 insertions(+), 72 deletions(-) create mode 100644 app/pages/admin/audit.vue create mode 100644 app/pages/admin/uploads.vue create mode 100644 app/pages/unsubscribe.vue create mode 100644 server/api/admin/audit.delete.ts create mode 100644 server/api/admin/audit.get.ts create mode 100644 server/api/admin/contacts/[id].patch.ts create mode 100644 server/api/admin/uploads.get.ts create mode 100644 server/api/admin/uploads/[name].delete.ts create mode 100644 server/api/auth/me.delete.ts create mode 100644 server/api/auth/password.patch.ts create mode 100644 server/api/newsletter/unsubscribe.post.ts create mode 100644 server/routes/feed.xml.ts create mode 100644 server/utils/audit.ts create mode 100644 server/utils/password.ts create mode 100644 tests/password.test.ts create mode 100644 tests/seed.test.ts create mode 100644 tests/validateContent.test.ts create mode 100644 vitest.config.ts diff --git a/app/app.vue b/app/app.vue index b68c4bf..1bc7239 100755 --- a/app/app.vue +++ b/app/app.vue @@ -1,21 +1,26 @@ diff --git a/app/pages/account.vue b/app/pages/account.vue index 6047f15..a40b525 100644 --- a/app/pages/account.vue +++ b/app/pages/account.vue @@ -87,6 +87,72 @@ {{ saving ? t('account.saving') : t('account.save') }}
+ + +
+

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

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

{{ pwMessage }}

+ +
+ + +
+

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

+

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

+
+ +
+

{{ deleteMessage }}

+ +
@@ -211,6 +277,72 @@ const saveProfile = async () => { saving.value = false } +// ---- 修改密码 ---- +const pwForm = reactive({ currentPassword: '', newPassword: '', confirmPassword: '' }) +const pwSaving = ref(false) +const pwMessage = ref('') +const pwFailed = ref(false) + +const changePassword = async () => { + pwMessage.value = '' + pwFailed.value = false + + if (pwForm.newPassword.length < 8) { + pwFailed.value = true + pwMessage.value = t('account.changePassword.tooShort') + return + } + if (pwForm.newPassword !== pwForm.confirmPassword) { + pwFailed.value = true + pwMessage.value = t('account.changePassword.mismatch') + return + } + + pwSaving.value = true + try { + await $fetch('/api/auth/password', { + method: 'PATCH', + body: { currentPassword: pwForm.currentPassword, newPassword: pwForm.newPassword }, + }) + pwMessage.value = t('account.changePassword.success') + pwForm.currentPassword = '' + pwForm.newPassword = '' + pwForm.confirmPassword = '' + } catch (err) { + pwFailed.value = true + pwMessage.value = + (err as any)?.data?.code === 'WRONG_PASSWORD' + ? t('account.changePassword.wrongPassword') + : apiError(err) + } + pwSaving.value = false +} + +// ---- 删除账号 ---- +const deletePassword = ref('') +const deleting = ref(false) +const deleteMessage = ref('') +const deleteFailed = ref(false) + +const confirmDeleteAccount = async () => { + if (!window.confirm(t('account.deleteAccount.confirmText'))) return + deleteMessage.value = '' + deleteFailed.value = false + deleting.value = true + try { + await $fetch('/api/auth/me', { method: 'DELETE', body: { password: deletePassword.value } }) + await userStore.logout() + await navigateTo('/') + } catch (err) { + deleteFailed.value = true + deleteMessage.value = + (err as any)?.data?.code === 'WRONG_PASSWORD' + ? t('account.deleteAccount.wrongPassword') + : apiError(err) + } + deleting.value = false +} + // ---- 收藏 ---- interface FavedWork { slug: string; titleZh: string; titleEn: string; image: string | null } const favorites = ref([]) diff --git a/app/pages/admin/audit.vue b/app/pages/admin/audit.vue new file mode 100644 index 0000000..61561ad --- /dev/null +++ b/app/pages/admin/audit.vue @@ -0,0 +1,227 @@ + + + diff --git a/app/pages/admin/comments.vue b/app/pages/admin/comments.vue index 76d8ab8..f50b945 100644 --- a/app/pages/admin/comments.vue +++ b/app/pages/admin/comments.vue @@ -41,7 +41,7 @@
- 共 {{ comments.length }} 条评论 + 共 {{ total }} 条评论 @@ -122,6 +122,18 @@
+ + +
+ +
@@ -140,9 +152,13 @@ interface AdminComment { username: string } +const pageSize = 20 +const page = ref(0) +const total = ref(0) const comments = ref([]) const keyword = ref('') const loading = ref(true) +const loadingMore = ref(false) const loadError = ref('') const filteredComments = computed(() => { @@ -169,8 +185,12 @@ const loadComments = async () => { loading.value = true loadError.value = '' try { - const data = await $fetch<{ comments: AdminComment[] }>('/api/admin/comments') + const data = await $fetch<{ comments: AdminComment[]; total: number; page: number }>('/api/admin/comments', { + query: { page: 1, pageSize }, + }) comments.value = data.comments + total.value = data.total + page.value = data.page } catch (err) { console.error('load comments error:', err) loadError.value = '加载失败,请重试' @@ -179,11 +199,30 @@ const loadComments = async () => { } } +const loadMore = async () => { + if (loadingMore.value || comments.value.length >= total.value) return + loadingMore.value = true + try { + const next = page.value + 1 + const data = await $fetch<{ comments: AdminComment[]; total: number; page: number }>('/api/admin/comments', { + query: { page: next, pageSize }, + }) + comments.value.push(...data.comments) + page.value = data.page + } catch (err) { + console.error('load more comments error:', err) + showFlash('加载更多失败,请重试', 'err') + } finally { + loadingMore.value = false + } +} + const removeComment = async (c: AdminComment) => { if (!window.confirm('确定删除这条评论吗?此操作不可恢复。')) return try { await $fetch(`/api/admin/comments/${c.id}`, { method: 'DELETE' }) comments.value = comments.value.filter((x) => x.id !== c.id) + total.value = Math.max(0, total.value - 1) showFlash('评论已删除') } catch (err) { console.error('delete comment error:', err) diff --git a/app/pages/admin/contacts.vue b/app/pages/admin/contacts.vue index 5c9eeef..92219ba 100644 --- a/app/pages/admin/contacts.vue +++ b/app/pages/admin/contacts.vue @@ -25,6 +25,7 @@
共 {{ contacts.length }} 条消息 · 已送达 {{ deliveredCount }} 条 + · 未读 {{ unreadCount }} 条
@@ -80,6 +81,23 @@ {{ Number(c.delivered) === 1 ? '已送达' : '未送达' }} + + + {{ Number(c.read) === 1 ? '已读' : '未读' }} + + + + + +

{{ copyFeedback }}

+ @@ -160,7 +192,7 @@ diff --git a/i18n/locales/en.json b/i18n/locales/en.json index 935978b..c682f75 100755 --- a/i18n/locales/en.json +++ b/i18n/locales/en.json @@ -427,7 +427,30 @@ "delivered": "Delivered to inbox", "notDelivered": "Not delivered (SMTP not configured)" }, - "adminEntry": "Admin Panel" + "adminEntry": "Admin Panel", + "changePassword": { + "title": "Change Password", + "currentPassword": "Current Password", + "newPassword": "New Password", + "confirmPassword": "Confirm New Password", + "submit": "Update Password", + "saving": "Updating...", + "success": "Password updated", + "failed": "Failed to update password", + "wrongPassword": "Current password is incorrect", + "tooShort": "New password must be at least 8 characters", + "mismatch": "Passwords do not match" + }, + "deleteAccount": { + "title": "Delete Account", + "hint": "This cannot be undone. Your comments and favorites will be removed.", + "passwordPlaceholder": "Enter your password to confirm", + "confirmButton": "Delete", + "cancelButton": "Cancel", + "success": "Account deleted", + "wrongPassword": "Incorrect password", + "confirmText": "Delete your account permanently? This cannot be undone." + } }, "comments": { "title": "Comments", @@ -466,5 +489,21 @@ "subscribed": "Subscribed! Thank you for joining.", "alreadySubscribed": "You are already subscribed", "error": "Subscription failed. Please try again." + }, + "error": { + "title": "Something went wrong", + "notFound": "Page not found", + "serverError": "Server error", + "generic": "An error occurred", + "backHome": "Back to Home" + }, + "unsubscribe": { + "title": "Unsubscribe", + "description": "Unsubscribe from ArcticNewOne newsletter:", + "unsubscribe": "Unsubscribe", + "unsubscribed": "You've been unsubscribed. Thanks for following along!", + "already": "This address is no longer subscribed.", + "invalid": "The unsubscribe link is invalid or has expired.", + "backHome": "Back to Home" } } diff --git a/i18n/locales/zh.json b/i18n/locales/zh.json index bf61d45..5029ea8 100755 --- a/i18n/locales/zh.json +++ b/i18n/locales/zh.json @@ -427,7 +427,30 @@ "delivered": "已送达邮箱", "notDelivered": "未送达(SMTP 未配置)" }, - "adminEntry": "进入后台管理" + "adminEntry": "进入后台管理", + "changePassword": { + "title": "修改密码", + "currentPassword": "当前密码", + "newPassword": "新密码", + "confirmPassword": "确认新密码", + "submit": "确认修改", + "saving": "提交中...", + "success": "密码已修改", + "failed": "修改失败,请重试", + "wrongPassword": "当前密码不正确", + "tooShort": "新密码至少需要 8 位", + "mismatch": "两次输入的新密码不一致" + }, + "deleteAccount": { + "title": "删除账号", + "hint": "删除后无法恢复,将同时清除你的评论与收藏。", + "passwordPlaceholder": "输入当前密码确认", + "confirmButton": "确认删除", + "cancelButton": "取消", + "success": "账号已删除", + "wrongPassword": "密码不正确", + "confirmText": "确定要永久删除账号吗?此操作不可撤销。" + } }, "comments": { "title": "评论", @@ -466,5 +489,21 @@ "subscribed": "订阅成功,感谢关注!", "alreadySubscribed": "您已在订阅列表中", "error": "订阅失败,请稍后再试" + }, + "error": { + "title": "出了点问题", + "notFound": "页面不存在", + "serverError": "服务器开小差了", + "generic": "发生了一个错误", + "backHome": "返回首页" + }, + "unsubscribe": { + "title": "退订", + "description": "确认退订 ArcticNewOne 资讯邮件:", + "unsubscribe": "确认退订", + "unsubscribed": "已成功退订。感谢你曾经的关注!", + "already": "该地址已不在订阅列表中。", + "invalid": "退订链接无效或已失效。", + "backHome": "返回首页" } } diff --git a/package.json b/package.json index c9a777b..97632fc 100755 --- a/package.json +++ b/package.json @@ -8,7 +8,8 @@ "generate": "nuxt generate", "preview": "nuxt preview", "postinstall": "nuxt prepare", - "start": "node .output/server/index.mjs" + "start": "node .output/server/index.mjs", + "test": "vitest run" }, "dependencies": { "@nuxt/hints": "1.0.3", @@ -28,6 +29,7 @@ "@iconify-json/ph": "1.2.2", "@nuxtjs/tailwindcss": "6.14.0", "@types/better-sqlite3": "^7.6.13", - "@types/nodemailer": "^6.4.17" + "@types/nodemailer": "^6.4.17", + "vitest": "^4.1.10" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6271b11..42bc546 100755 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10,7 +10,7 @@ importers: dependencies: '@nuxt/hints': specifier: 1.0.3 - version: 1.0.3(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)(better-sqlite3@13.0.2)(db0@0.3.4(better-sqlite3@13.0.2))(ioredis@5.10.1(supports-color@10.2.2))(magicast@0.5.2)(srvx@0.11.15)(supports-color@10.2.2)(typescript@6.0.3)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))(vue@3.5.33(typescript@6.0.3)) + version: 1.0.3(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)(better-sqlite3@13.0.2)(db0@0.3.4(better-sqlite3@13.0.2))(ioredis@5.10.1(supports-color@10.2.2))(magicast@0.5.2)(srvx@0.11.15)(supports-color@10.2.2)(typescript@6.0.3)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))(vitest@4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)))(vue@3.5.33(typescript@6.0.3)) '@nuxt/icon': specifier: 2.2.1 version: 2.2.1(magicast@0.5.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))(vue@3.5.33(typescript@6.0.3)) @@ -57,6 +57,9 @@ importers: '@types/nodemailer': specifier: ^6.4.17 version: 6.4.24 + vitest: + specifier: ^4.1.10 + version: 4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)) packages: @@ -2005,12 +2008,21 @@ packages: '@speed-highlight/core@1.2.15': resolution: {integrity: sha512-BMq1K3DsElxDWawkX6eLg9+CKJrTVGCBAWVuHXVUV2u0s2711qiChLSId6ikYPfxhdYocLNt3wWwSvDiTvFabw==} + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@tybys/wasm-util@0.10.1': resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==} '@types/better-sqlite3@7.6.13': resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==} + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + '@types/esrecurse@4.3.1': resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==} @@ -2086,6 +2098,35 @@ packages: vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 vue: ^3.2.25 + '@vitest/expect@4.1.10': + resolution: {integrity: sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==} + + '@vitest/mocker@4.1.10': + resolution: {integrity: sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@4.1.10': + resolution: {integrity: sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==} + + '@vitest/runner@4.1.10': + resolution: {integrity: sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==} + + '@vitest/snapshot@4.1.10': + resolution: {integrity: sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==} + + '@vitest/spy@4.1.10': + resolution: {integrity: sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==} + + '@vitest/utils@4.1.10': + resolution: {integrity: sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==} + '@vue-macros/common@3.1.2': resolution: {integrity: sha512-h9t4ArDdniO9ekYHAD95t9AZcAbb19lEGK+26iAjUODOIJKmObDNBSe4+6ELQAA3vtYiFPPBtHh7+cQCKi3Dng==} engines: {node: '>=20.19.0'} @@ -2244,6 +2285,10 @@ packages: argparse@2.0.1: resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + ast-kit@2.2.0: resolution: {integrity: sha512-m1Q/RaVOnTp9JxPX+F+Zn7IcLYMzM8kZofDImfsKZd8MbR+ikdOzTeztStWqfrqIxZnYWryyI9ePm3NGjnZgGw==} engines: {node: '>=20.19.0'} @@ -2420,6 +2465,10 @@ packages: caniuse-lite@1.0.30001790: resolution: {integrity: sha512-bOoxfJPyYo+ds6W0YfptaCWbFnJYjh2Y1Eow5lRv+vI2u8ganPZqNm1JwNh0t2ELQCqIWg4B3dWEusgAmsoyOw==} + chai@6.2.2: + resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} + engines: {node: '>=18'} + chalk@4.1.2: resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} engines: {node: '>=10'} @@ -2913,6 +2962,10 @@ packages: resolution: {integrity: sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==} engines: {node: '>=16.17'} + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + exsolve@1.0.8: resolution: {integrity: sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==} @@ -4313,6 +4366,9 @@ packages: resolution: {integrity: sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==} engines: {node: '>= 0.4'} + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + signal-exit@4.1.0: resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} engines: {node: '>=14'} @@ -4359,6 +4415,9 @@ packages: engines: {node: '>=20.16.0'} hasBin: true + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + standard-as-callback@2.1.0: resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==} @@ -4495,6 +4554,9 @@ packages: tiny-invariant@1.3.3: resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==} + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + tinyclip@0.1.12: resolution: {integrity: sha512-Ae3OVUqifDw0wBriIBS7yVaW44Dp6eSHQcyq4Igc7eN2TJH/2YsicswaW+J/OuMvhpDPOKEgpAZCjkb4hpoyeA==} engines: {node: ^16.14.0 || >= 17.3.0} @@ -4507,6 +4569,10 @@ packages: resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} engines: {node: '>=12.0.0'} + tinyrainbow@3.1.1: + resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==} + engines: {node: '>=14.0.0'} + to-regex-range@5.0.1: resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} engines: {node: '>=8.0'} @@ -4822,6 +4888,47 @@ packages: yaml: optional: true + vitest@4.1.10: + resolution: {integrity: sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==} + engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 4.1.10 + '@vitest/browser-preview': 4.1.10 + '@vitest/browser-webdriverio': 4.1.10 + '@vitest/coverage-istanbul': 4.1.10 + '@vitest/coverage-v8': 4.1.10 + '@vitest/ui': 4.1.10 + happy-dom: '*' + jsdom: '*' + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + vscode-uri@3.1.0: resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==} @@ -4882,6 +4989,11 @@ packages: engines: {node: ^20.17.0 || >=22.9.0} hasBin: true + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + word-wrap@1.2.5: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} @@ -5710,7 +5822,7 @@ snapshots: - utf-8-validate - vue - '@nuxt/hints@1.0.3(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)(better-sqlite3@13.0.2)(db0@0.3.4(better-sqlite3@13.0.2))(ioredis@5.10.1(supports-color@10.2.2))(magicast@0.5.2)(srvx@0.11.15)(supports-color@10.2.2)(typescript@6.0.3)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))(vue@3.5.33(typescript@6.0.3))': + '@nuxt/hints@1.0.3(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)(better-sqlite3@13.0.2)(db0@0.3.4(better-sqlite3@13.0.2))(ioredis@5.10.1(supports-color@10.2.2))(magicast@0.5.2)(srvx@0.11.15)(supports-color@10.2.2)(typescript@6.0.3)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))(vitest@4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)))(vue@3.5.33(typescript@6.0.3))': dependencies: '@nuxt/devtools-kit': 3.2.4(magicast@0.5.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)) '@nuxt/kit': 4.4.2(magicast@0.5.2) @@ -5718,7 +5830,7 @@ snapshots: defu: 6.1.7 devalue: 5.7.1 h3: 1.15.11 - html-validate: 10.13.1 + html-validate: 10.13.1(vitest@4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))) knitwork: 1.3.0 magic-string: 0.30.21 nitropack: 2.13.3(better-sqlite3@13.0.2)(srvx@0.11.15)(supports-color@10.2.2) @@ -6733,6 +6845,8 @@ snapshots: '@speed-highlight/core@1.2.15': {} + '@standard-schema/spec@1.1.0': {} + '@tybys/wasm-util@0.10.1': dependencies: tslib: 2.8.1 @@ -6742,6 +6856,13 @@ snapshots: dependencies: '@types/node': 26.1.2 + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + '@types/esrecurse@4.3.1': {} '@types/estree@1.0.8': {} @@ -6843,6 +6964,47 @@ snapshots: vite: 7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3) vue: 3.5.33(typescript@6.0.3) + '@vitest/expect@4.1.10': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 4.1.10 + '@vitest/utils': 4.1.10 + chai: 6.2.2 + tinyrainbow: 3.1.1 + + '@vitest/mocker@4.1.10(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))': + dependencies: + '@vitest/spy': 4.1.10 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3) + + '@vitest/pretty-format@4.1.10': + dependencies: + tinyrainbow: 3.1.1 + + '@vitest/runner@4.1.10': + dependencies: + '@vitest/utils': 4.1.10 + pathe: 2.0.3 + + '@vitest/snapshot@4.1.10': + dependencies: + '@vitest/pretty-format': 4.1.10 + '@vitest/utils': 4.1.10 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@4.1.10': {} + + '@vitest/utils@4.1.10': + dependencies: + '@vitest/pretty-format': 4.1.10 + convert-source-map: 2.0.0 + tinyrainbow: 3.1.1 + '@vue-macros/common@3.1.2(vue@3.5.33(typescript@6.0.3))': dependencies: '@vue/compiler-sfc': 3.5.33 @@ -7059,6 +7221,8 @@ snapshots: argparse@2.0.1: {} + assertion-error@2.0.1: {} + ast-kit@2.2.0: dependencies: '@babel/parser': 7.29.2 @@ -7225,6 +7389,8 @@ snapshots: caniuse-lite@1.0.30001790: {} + chai@6.2.2: {} + chalk@4.1.2: dependencies: ansi-styles: 4.3.0 @@ -7733,6 +7899,8 @@ snapshots: signal-exit: 4.1.0 strip-final-newline: 3.0.0 + expect-type@1.4.0: {} + exsolve@1.0.8: {} exsolve@1.1.1: {} @@ -7941,7 +8109,7 @@ snapshots: hookable@6.1.1: {} - html-validate@10.13.1: + html-validate@10.13.1(vitest@4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))): dependencies: '@html-validate/stylish': 5.2.0 '@sidvind/better-ajv-errors': 5.0.0(ajv@8.20.0) @@ -7951,6 +8119,8 @@ snapshots: minimist: 1.2.8 prompts: 2.4.2 semver: 7.7.4 + optionalDependencies: + vitest: 4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)) http-assert@1.5.0: dependencies: @@ -9433,6 +9603,8 @@ snapshots: shell-quote@1.8.3: {} + siginfo@2.0.0: {} + signal-exit@4.1.0: {} simple-git@3.36.0(supports-color@10.2.2): @@ -9472,6 +9644,8 @@ snapshots: srvx@0.11.15: {} + stackback@0.0.2: {} + standard-as-callback@2.1.0: {} statuses@1.5.0: {} @@ -9669,6 +9843,8 @@ snapshots: tiny-invariant@1.3.3: {} + tinybench@2.9.0: {} + tinyclip@0.1.12: {} tinyexec@1.1.1: {} @@ -9678,6 +9854,8 @@ snapshots: fdir: 6.5.0(picomatch@4.0.4) picomatch: 4.0.4 + tinyrainbow@3.1.1: {} + to-regex-range@5.0.1: dependencies: is-number: 7.0.0 @@ -9932,6 +10110,33 @@ snapshots: terser: 5.46.2 yaml: 2.8.3 + vitest@4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)): + dependencies: + '@vitest/expect': 4.1.10 + '@vitest/mocker': 4.1.10(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)) + '@vitest/pretty-format': 4.1.10 + '@vitest/runner': 4.1.10 + '@vitest/snapshot': 4.1.10 + '@vitest/spy': 4.1.10 + '@vitest/utils': 4.1.10 + es-module-lexer: 2.1.0 + expect-type: 1.4.0 + magic-string: 0.30.21 + obug: 2.1.1 + pathe: 2.0.3 + picomatch: 4.0.4 + std-env: 4.1.0 + tinybench: 2.9.0 + tinyexec: 1.1.1 + tinyglobby: 0.2.16 + tinyrainbow: 3.1.1 + vite: 7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 26.1.2 + transitivePeerDependencies: + - msw + vscode-uri@3.1.0: {} vue-bundle-renderer@2.2.0: @@ -10001,6 +10206,11 @@ snapshots: dependencies: isexe: 4.0.0 + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + word-wrap@1.2.5: {} wrap-ansi@7.0.0: diff --git a/server/api/admin/articles.post.ts b/server/api/admin/articles.post.ts index 0c8611e..ba3ccbe 100644 --- a/server/api/admin/articles.post.ts +++ b/server/api/admin/articles.post.ts @@ -2,6 +2,7 @@ import { readBody, createError } from 'h3' import { requireAdmin } from '../../utils/auth' import { getDb } from '../../utils/db' import { getArticleBySlug } from '../../utils/content' +import { writeAudit } from '../../utils/audit' import { normalizeSlug, isValidSlug, isValidArticleCategory, normalizeBlocks } from '../../utils/validateContent' /** @@ -48,5 +49,7 @@ export default defineEventHandler(async (event) => { body?.published ? 1 : 0, ) + writeAudit(event, 'create', `article:${slug}`) + return { ok: true, article: getArticleBySlug(slug, { publishedOnly: false }) } }) diff --git a/server/api/admin/articles/[id].delete.ts b/server/api/admin/articles/[id].delete.ts index cb48417..7413a60 100644 --- a/server/api/admin/articles/[id].delete.ts +++ b/server/api/admin/articles/[id].delete.ts @@ -1,6 +1,7 @@ import { createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台删除动态(连带删除其评论) @@ -21,5 +22,6 @@ export default defineEventHandler((event) => { }) tx() - return { ok: true } + writeAudit(event, 'delete', `article:${row.slug}`) +return { ok: true } }) diff --git a/server/api/admin/articles/[id].patch.ts b/server/api/admin/articles/[id].patch.ts index 69ed000..b396e71 100644 --- a/server/api/admin/articles/[id].patch.ts +++ b/server/api/admin/articles/[id].patch.ts @@ -3,6 +3,7 @@ import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' import { getArticleBySlug } from '../../../utils/content' import { normalizeSlug, isValidSlug, isValidArticleCategory, normalizeBlocks } from '../../../utils/validateContent' +import { writeAudit } from '../../../utils/audit' /** * 后台更新动态(部分字段) @@ -69,7 +70,8 @@ export default defineEventHandler(async (event) => { db.prepare(`UPDATE articles SET ${sets.join(', ')} WHERE id = ?`).run(...params, id) const row = db.prepare('SELECT slug FROM articles WHERE id = ?').get(id) as { slug: string } - return { ok: true, article: getArticleBySlug(row.slug, { publishedOnly: false }) } + writeAudit(event, 'update', `article:${id}`) +return { ok: true, article: getArticleBySlug(row.slug, { publishedOnly: false }) } }) function fieldToCol(field: string): string { diff --git a/server/api/admin/audit.delete.ts b/server/api/admin/audit.delete.ts new file mode 100644 index 0000000..d4ca24c --- /dev/null +++ b/server/api/admin/audit.delete.ts @@ -0,0 +1,13 @@ +import { requireAdmin } from '../../utils/auth' +import { getDb } from '../../utils/db' +import { writeAudit } from '../../utils/audit' + +/** + * 清空审计日志 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + getDb().prepare('DELETE FROM audit_logs').run() + writeAudit(event, 'clear', 'audit') + return { ok: true } +}) diff --git a/server/api/admin/audit.get.ts b/server/api/admin/audit.get.ts new file mode 100644 index 0000000..49c49c3 --- /dev/null +++ b/server/api/admin/audit.get.ts @@ -0,0 +1,24 @@ +import { getQuery } from 'h3' +import { requireAdmin } from '../../utils/auth' +import { getDb } from '../../utils/db' + +/** + * 后台操作审计日志(分页) + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const q = getQuery(event) + const page = Math.max(1, Number(q?.page) || 1) + const pageSize = Math.min(100, Math.max(1, Number(q?.pageSize) || 20)) + + const db = getDb() + const total = (db.prepare('SELECT COUNT(*) AS c FROM audit_logs').get() as { c: number }).c + const logs = db + .prepare( + `SELECT id, actor_id, actor_name, action, target, detail, created_at AS createdAt + FROM audit_logs ORDER BY created_at DESC LIMIT ? OFFSET ?`, + ) + .all(pageSize, (page - 1) * pageSize) + + return { logs, total, page, pageSize } +}) diff --git a/server/api/admin/comments.get.ts b/server/api/admin/comments.get.ts index b10e744..3a270eb 100644 --- a/server/api/admin/comments.get.ts +++ b/server/api/admin/comments.get.ts @@ -1,18 +1,26 @@ +import { getQuery } from 'h3' import { requireAdmin } from '../../utils/auth' import { getDb } from '../../utils/db' /** - * 后台全站评论列表(含文章 slug 与作者) + * 后台全站评论列表(分页) */ export default defineEventHandler((event) => { requireAdmin(event) - const comments = getDb() + const q = getQuery(event) + const page = Math.max(1, Number(q?.page) || 1) + const pageSize = Math.min(100, Math.max(1, Number(q?.pageSize) || 20)) + + const db = getDb() + const total = (db.prepare('SELECT COUNT(*) AS c FROM comments').get() as { c: number }).c + const comments = db .prepare( `SELECT c.id, c.news_slug AS newsSlug, c.content, c.created_at AS createdAt, u.username FROM comments c JOIN users u ON u.id = c.user_id - ORDER BY c.created_at DESC`, + ORDER BY c.created_at DESC LIMIT ? OFFSET ?`, ) - .all() - return { comments } + .all(pageSize, (page - 1) * pageSize) + + return { comments, total, page, pageSize } }) diff --git a/server/api/admin/comments/[id].delete.ts b/server/api/admin/comments/[id].delete.ts index b5e44c9..d2eb0c1 100644 --- a/server/api/admin/comments/[id].delete.ts +++ b/server/api/admin/comments/[id].delete.ts @@ -1,6 +1,7 @@ import { createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台删除评论 @@ -14,5 +15,6 @@ export default defineEventHandler((event) => { throw createError({ statusCode: 404, message: '评论不存在', data: { code: 'NOT_FOUND' } }) } db.prepare('DELETE FROM comments WHERE id = ?').run(id) - return { ok: true } + writeAudit(event, 'delete', `comment:${id}`) +return { ok: true } }) diff --git a/server/api/admin/contacts.get.ts b/server/api/admin/contacts.get.ts index 65961b3..14268a7 100644 --- a/server/api/admin/contacts.get.ts +++ b/server/api/admin/contacts.get.ts @@ -7,7 +7,7 @@ import { getDb } from '../../utils/db' export default defineEventHandler((event) => { requireAdmin(event) const contacts = getDb() - .prepare('SELECT id, name, email, subject, message, delivered, created_at AS createdAt FROM contacts ORDER BY created_at DESC') + .prepare('SELECT id, name, email, subject, message, delivered, read, created_at AS createdAt FROM contacts ORDER BY created_at DESC') .all() return { contacts } }) diff --git a/server/api/admin/contacts/[id].delete.ts b/server/api/admin/contacts/[id].delete.ts index 2eeb142..73dba21 100644 --- a/server/api/admin/contacts/[id].delete.ts +++ b/server/api/admin/contacts/[id].delete.ts @@ -1,6 +1,7 @@ import { createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台删除联系消息 @@ -14,5 +15,6 @@ export default defineEventHandler((event) => { throw createError({ statusCode: 404, message: '消息不存在', data: { code: 'NOT_FOUND' } }) } db.prepare('DELETE FROM contacts WHERE id = ?').run(id) - return { ok: true } + writeAudit(event, 'delete', `contact:${id}`) +return { ok: true } }) diff --git a/server/api/admin/contacts/[id].patch.ts b/server/api/admin/contacts/[id].patch.ts new file mode 100644 index 0000000..2fb1d1f --- /dev/null +++ b/server/api/admin/contacts/[id].patch.ts @@ -0,0 +1,25 @@ +import { readBody, createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' + +/** + * 后台更新联系消息(已读/未读标记) + */ +export default defineEventHandler(async (event) => { + requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const body = await readBody(event) + const db = getDb() + + const target = db.prepare('SELECT id FROM contacts WHERE id = ?').get(id) + if (!target) { + throw createError({ statusCode: 404, message: '消息不存在', data: { code: 'NOT_FOUND' } }) + } + + if (body?.read !== undefined) { + db.prepare('UPDATE contacts SET read = ? WHERE id = ?').run(body.read ? 1 : 0, id) + writeAudit(event, 'update', `contact:${id}`, `read=${body.read ? 1 : 0}`) + } + return { ok: true } +}) diff --git a/server/api/admin/subscribers/[id].delete.ts b/server/api/admin/subscribers/[id].delete.ts index 1f42424..3d5296e 100644 --- a/server/api/admin/subscribers/[id].delete.ts +++ b/server/api/admin/subscribers/[id].delete.ts @@ -1,6 +1,7 @@ import { createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台删除订阅 @@ -14,5 +15,6 @@ export default defineEventHandler((event) => { throw createError({ statusCode: 404, message: '订阅不存在', data: { code: 'NOT_FOUND' } }) } db.prepare('DELETE FROM subscribers WHERE id = ?').run(id) - return { ok: true } + writeAudit(event, 'delete', `subscriber:${id}`) +return { ok: true } }) diff --git a/server/api/admin/upload.post.ts b/server/api/admin/upload.post.ts index d3c5742..a73d73f 100644 --- a/server/api/admin/upload.post.ts +++ b/server/api/admin/upload.post.ts @@ -4,6 +4,7 @@ import { dirname, join } from 'node:path' import { randomBytes } from 'node:crypto' import { requireAdmin } from '../../utils/auth' import { getConfig } from '../../utils/config' +import { writeAudit } from '../../utils/audit' const MAX_SIZE = 8 * 1024 * 1024 // 8MB const EXT_BY_TYPE: Record = { @@ -42,5 +43,6 @@ export default defineEventHandler(async (event) => { mkdirSync(dir, { recursive: true }) writeFileSync(join(dir, name), file.data) - return { ok: true, url: `/uploads/${name}` } + writeAudit(event, 'upload', `upload:${name}`) +return { ok: true, url: `/uploads/${name}` } }) diff --git a/server/api/admin/uploads.get.ts b/server/api/admin/uploads.get.ts new file mode 100644 index 0000000..84432e1 --- /dev/null +++ b/server/api/admin/uploads.get.ts @@ -0,0 +1,27 @@ +import { requireAdmin } from '../../utils/auth' +import { getConfig } from '../../utils/config' +import { readdirSync, statSync } from 'node:fs' +import { join, dirname } from 'node:path' + +/** + * 后台图片管理:列出 /data/uploads 下的文件 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const dir = join(dirname(getConfig().dbPath), 'uploads') + + const files: Array<{ name: string; size: number; modified: string; url: string }> = [] + try { + for (const name of readdirSync(dir)) { + const p = join(dir, name) + const st = statSync(p) + if (!st.isFile()) continue + files.push({ name, size: st.size, modified: st.mtime.toISOString(), url: `/uploads/${name}` }) + } + } catch { + // 目录可能尚不存在 + } + + files.sort((a, b) => b.modified.localeCompare(a.modified)) + return { files } +}) diff --git a/server/api/admin/uploads/[name].delete.ts b/server/api/admin/uploads/[name].delete.ts new file mode 100644 index 0000000..b090bf9 --- /dev/null +++ b/server/api/admin/uploads/[name].delete.ts @@ -0,0 +1,28 @@ +import { createError } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getConfig } from '../../../utils/config' +import { writeAudit } from '../../../utils/audit' +import { unlinkSync, existsSync } from 'node:fs' +import { join, dirname } from 'node:path' + +/** + * 后台删除上传的图片 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const name = getRouterParam(event, 'name') ?? '' + + // 防目录穿越:仅允许纯文件名 + if (!name || name.includes('/') || name.includes('\\') || name.includes('..')) { + throw createError({ statusCode: 400, message: '非法文件名', data: { code: 'VALIDATION_ERROR' } }) + } + + const filePath = join(dirname(getConfig().dbPath), 'uploads', name) + if (!existsSync(filePath)) { + throw createError({ statusCode: 404, message: '文件不存在', data: { code: 'NOT_FOUND' } }) + } + + unlinkSync(filePath) + writeAudit(event, 'delete', `upload:${name}`) + return { ok: true } +}) diff --git a/server/api/admin/users/[id].delete.ts b/server/api/admin/users/[id].delete.ts index 5b235f9..af96ce3 100644 --- a/server/api/admin/users/[id].delete.ts +++ b/server/api/admin/users/[id].delete.ts @@ -1,6 +1,7 @@ import { createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台删除用户(连带删除其会话/评论/收藏) @@ -18,5 +19,6 @@ export default defineEventHandler((event) => { throw createError({ statusCode: 404, message: '用户不存在', data: { code: 'NOT_FOUND' } }) } db.prepare('DELETE FROM users WHERE id = ?').run(id) // 外键级联:sessions/comments/favorites - return { ok: true } + writeAudit(event, 'delete', `user:${id}`) +return { ok: true } }) diff --git a/server/api/admin/users/[id].patch.ts b/server/api/admin/users/[id].patch.ts index 9cb9aa9..0a2efda 100644 --- a/server/api/admin/users/[id].patch.ts +++ b/server/api/admin/users/[id].patch.ts @@ -1,6 +1,7 @@ import { readBody, createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台更新用户(角色切换) @@ -24,5 +25,6 @@ export default defineEventHandler(async (event) => { } db.prepare('UPDATE users SET role = ? WHERE id = ?').run(body.role, id) } - return { ok: true } + writeAudit(event, 'update', `user:${id}`) +return { ok: true } }) diff --git a/server/api/admin/works.post.ts b/server/api/admin/works.post.ts index 019986e..17cc5de 100644 --- a/server/api/admin/works.post.ts +++ b/server/api/admin/works.post.ts @@ -2,6 +2,7 @@ import { readBody, createError } from 'h3' import { requireAdmin } from '../../utils/auth' import { getDb } from '../../utils/db' import { getWorkBySlug } from '../../utils/content' +import { writeAudit } from '../../utils/audit' import { normalizeSlug, isValidSlug, @@ -65,5 +66,6 @@ export default defineEventHandler(async (event) => { body?.published ? 1 : 0, ) - return { ok: true, work: getWorkBySlug(slug, { publishedOnly: false }) } + writeAudit(event, 'create', `work:${slug}`) +return { ok: true, work: getWorkBySlug(slug, { publishedOnly: false }) } }) diff --git a/server/api/admin/works/[id].delete.ts b/server/api/admin/works/[id].delete.ts index b692945..a7f52ab 100644 --- a/server/api/admin/works/[id].delete.ts +++ b/server/api/admin/works/[id].delete.ts @@ -1,6 +1,7 @@ import { createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台删除作品(连带清理用户收藏) @@ -21,5 +22,6 @@ export default defineEventHandler((event) => { }) tx() - return { ok: true } + writeAudit(event, 'delete', `work:${row.slug}`) +return { ok: true } }) diff --git a/server/api/admin/works/[id].patch.ts b/server/api/admin/works/[id].patch.ts index 242ab13..0ee5835 100644 --- a/server/api/admin/works/[id].patch.ts +++ b/server/api/admin/works/[id].patch.ts @@ -2,6 +2,7 @@ import { readBody, createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' import { getWorkBySlug } from '../../../utils/content' +import { writeAudit } from '../../../utils/audit' import { normalizeSlug, isValidSlug, @@ -77,7 +78,8 @@ export default defineEventHandler(async (event) => { db.prepare(`UPDATE works SET ${sets.join(', ')} WHERE id = ?`).run(...params, id) const row = db.prepare('SELECT slug FROM works WHERE id = ?').get(id) as { slug: string } - return { ok: true, work: getWorkBySlug(row.slug, { publishedOnly: false }) } + writeAudit(event, 'update', `work:${id}`) +return { ok: true, work: getWorkBySlug(row.slug, { publishedOnly: false }) } }) function fieldToCol(field: string): string { diff --git a/server/api/auth/me.delete.ts b/server/api/auth/me.delete.ts new file mode 100644 index 0000000..d205c78 --- /dev/null +++ b/server/api/auth/me.delete.ts @@ -0,0 +1,23 @@ +import { readBody, createError } from 'h3' +import { getDb } from '../../utils/db' +import { requireUser, verifyPassword, clearSessionCookie } from '../../utils/auth' + +/** + * 自助删除账号(需验证当前密码;删除后登出,级联清理会话/评论/收藏) + */ +export default defineEventHandler(async (event) => { + const user = requireUser(event) + const body = await readBody(event) + const password = String(body?.password ?? '') + + const row = getDb().prepare('SELECT password_hash FROM users WHERE id = ?').get(user.id) as + | { password_hash: string } + | undefined + if (!row || !(await verifyPassword(password, row.password_hash))) { + throw createError({ statusCode: 400, message: '密码不正确', data: { code: 'WRONG_PASSWORD' } }) + } + + getDb().prepare('DELETE FROM users WHERE id = ?').run(user.id) // 外键级联:sessions/comments/favorites + clearSessionCookie(event) + return { ok: true } +}) diff --git a/server/api/auth/password.patch.ts b/server/api/auth/password.patch.ts new file mode 100644 index 0000000..7cd8184 --- /dev/null +++ b/server/api/auth/password.patch.ts @@ -0,0 +1,28 @@ +import { readBody, createError } from 'h3' +import { getDb } from '../../utils/db' +import { requireUser, verifyPassword, hashPassword } from '../../utils/auth' +import { isValidPassword } from '../../utils/validation' + +/** + * 修改密码:校验当前密码 -> 新密码强度 -> 更新 + */ +export default defineEventHandler(async (event) => { + const user = requireUser(event) + const body = await readBody(event) + const currentPassword = String(body?.currentPassword ?? '') + const newPassword = String(body?.newPassword ?? '') + + const row = getDb().prepare('SELECT password_hash FROM users WHERE id = ?').get(user.id) as + | { password_hash: string } + | undefined + if (!row || !(await verifyPassword(currentPassword, row.password_hash))) { + throw createError({ statusCode: 400, message: '当前密码不正确', data: { code: 'WRONG_PASSWORD' } }) + } + if (!isValidPassword(newPassword)) { + throw createError({ statusCode: 400, message: '新密码至少需要 8 位', data: { code: 'VALIDATION_ERROR' } }) + } + + const passwordHash = await hashPassword(newPassword) + getDb().prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(passwordHash, user.id) + return { ok: true } +}) diff --git a/server/api/newsletter.post.ts b/server/api/newsletter.post.ts index 6e37ecb..7f0f56a 100644 --- a/server/api/newsletter.post.ts +++ b/server/api/newsletter.post.ts @@ -1,10 +1,12 @@ import { readBody, createError } from 'h3' +import { randomBytes } from 'node:crypto' import { getDb } from '../utils/db' +import { getConfig } from '../utils/config' import { sendMail } from '../utils/email' import { isValidEmail } from '../utils/validation' /** - * 邮箱订阅:去重落库 + 尽力发送欢迎邮件 + * 邮箱订阅:去重落库(生成退订 token)+ 尽力发送欢迎邮件 */ export default defineEventHandler(async (event) => { const body = await readBody(event) @@ -20,13 +22,16 @@ export default defineEventHandler(async (event) => { throw createError({ statusCode: 400, message: '您已在订阅列表中', data: { code: 'ALREADY_SUBSCRIBED' } }) } - db.prepare('INSERT INTO subscribers (email) VALUES (?)').run(email) + const token = randomBytes(24).toString('hex') + db.prepare('INSERT INTO subscribers (email, token) VALUES (?, ?)').run(email, token) + const { siteUrl } = getConfig() + const unsubscribeUrl = siteUrl ? `${siteUrl}/unsubscribe?token=${token}` : '' await sendMail( email, '欢迎订阅 ArcticNewOne 资讯', - '感谢订阅 ArcticNewOne!我们会不定期发送精选更新,助您把握设计、开发与行业动态。', + `感谢订阅 ArcticNewOne!我们会不定期发送精选更新,助您把握设计、开发与行业动态。\n\n如需退订:${unsubscribeUrl || '请联系管理员'}`, ) - return { ok: true } + return { ok: true, token } }) diff --git a/server/api/newsletter/unsubscribe.post.ts b/server/api/newsletter/unsubscribe.post.ts new file mode 100644 index 0000000..62cb9fc --- /dev/null +++ b/server/api/newsletter/unsubscribe.post.ts @@ -0,0 +1,24 @@ +import { readBody, createError } from 'h3' +import { getDb } from '../../utils/db' + +/** + * 订阅退订(基于订阅时生成的 token;幂等,无效 token 不报错避免泄露) + */ +export default defineEventHandler(async (event) => { + const body = await readBody(event) + const token = String(body?.token ?? '') + if (!token) { + throw createError({ statusCode: 400, message: '缺少退订标识', data: { code: 'VALIDATION_ERROR' } }) + } + + const db = getDb() + const sub = db.prepare('SELECT id FROM subscribers WHERE token = ?').get(token) as + | { id: number } + | undefined + + if (!sub) { + return { ok: true, unsubscribed: false } + } + db.prepare('DELETE FROM subscribers WHERE id = ?').run(sub.id) + return { ok: true, unsubscribed: true } +}) diff --git a/server/routes/feed.xml.ts b/server/routes/feed.xml.ts new file mode 100644 index 0000000..62b3a54 --- /dev/null +++ b/server/routes/feed.xml.ts @@ -0,0 +1,51 @@ +import { getConfig } from '../utils/config' +import { listArticles } from '../utils/content' + +const escapeXml = (s: string) => + String(s ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + +/** + * RSS 2.0 订阅源 /feed.xml(动态全部已发布) + */ +export default defineEventHandler(() => { + const { siteUrl } = getConfig() + const articles = listArticles({ publishedOnly: true }) + + const items = articles + .map((a) => { + const title = a.titleZh || a.titleEn + const desc = a.excerptZh || a.excerptEn + const link = `${siteUrl}/news/${a.slug}` + const date = a.date ? new Date(`${a.date}T00:00:00Z`).toUTCString() : new Date().toUTCString() + return [ + ' ', + ` ${escapeXml(title)}`, + ` ${link}`, + ` ${link}`, + ` ${escapeXml(desc)}`, + ` ${date}`, + ' ', + ].join('\n') + }) + .join('\n') + + const xml = ` + + + ArcticNewOne + ${siteUrl} + 北极新一工作室的最新动态与洞察 + zh-cn + +${items} + +` + + return new Response(xml, { + headers: { 'Content-Type': 'application/rss+xml; charset=utf-8' }, + }) +}) diff --git a/server/utils/audit.ts b/server/utils/audit.ts new file mode 100644 index 0000000..dd66394 --- /dev/null +++ b/server/utils/audit.ts @@ -0,0 +1,18 @@ +import type { H3Event } from 'h3' +import { getDb } from './db' +import { getCurrentUser } from './auth' + +/** + * 记录后台操作审计日志(增删改内容/用户/评论/联系/订阅/上传等)。 + * 写入失败不影响主流程(仅记录日志)。 + */ +export function writeAudit(event: H3Event, action: string, target: string, detail?: string): void { + try { + const user = getCurrentUser(event) + getDb() + .prepare('INSERT INTO audit_logs (actor_id, actor_name, action, target, detail) VALUES (?, ?, ?, ?, ?)') + .run(user?.id ?? null, user?.username ?? 'system', action, target, detail ?? null) + } catch (err) { + console.error('[audit] write failed:', err) + } +} diff --git a/server/utils/auth.ts b/server/utils/auth.ts index f41550d..90392ea 100644 --- a/server/utils/auth.ts +++ b/server/utils/auth.ts @@ -1,14 +1,10 @@ -import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto' -import { promisify } from 'node:util' +import { randomBytes } from 'node:crypto' import { createError, getCookie, setCookie, deleteCookie } from 'h3' import type { H3Event } from 'h3' import { getDb } from './db' +import { hashPassword, verifyPassword } from './password' -const scryptAsync = promisify(scrypt) as ( - password: string, - salt: string, - keylen: number, -) => Promise +export { hashPassword, verifyPassword } export interface UserRow { id: number @@ -22,22 +18,6 @@ export interface UserRow { export const SESSION_COOKIE = 'an_session' const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60 // 30 天 -// ---------- 密码哈希(scrypt,盐 + 哈希以冒号分隔存储) ---------- - -export async function hashPassword(password: string): Promise { - const salt = randomBytes(16).toString('hex') - const key = await scryptAsync(password, salt, 64) - return `${salt}:${key.toString('hex')}` -} - -export async function verifyPassword(password: string, stored: string): Promise { - const [salt, hash] = stored.split(':') - if (!salt || !hash) return false - const key = await scryptAsync(password, salt, 64) - const expected = Buffer.from(hash, 'hex') - return key.length === expected.length && timingSafeEqual(key, expected) -} - // ---------- 会话 ---------- export function createSession(userId: number): string { diff --git a/server/utils/db.ts b/server/utils/db.ts index 6f70923..f2e384e 100644 --- a/server/utils/db.ts +++ b/server/utils/db.ts @@ -70,12 +70,14 @@ function migrate(db: Database.Database): void { subject TEXT NOT NULL, message TEXT NOT NULL, delivered INTEGER NOT NULL DEFAULT 0, + read INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS subscribers ( id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT NOT NULL UNIQUE, + token TEXT, created_at TEXT NOT NULL DEFAULT (datetime('now')) ); @@ -152,7 +154,32 @@ function migrate(db: Database.Database): void { CREATE INDEX IF NOT EXISTS idx_works_category ON works(category); CREATE INDEX IF NOT EXISTS idx_works_published ON works(published); + + -- 后台操作审计日志 + CREATE TABLE IF NOT EXISTS audit_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + actor_id INTEGER, + actor_name TEXT, + action TEXT NOT NULL, + target TEXT NOT NULL, + detail TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE INDEX IF NOT EXISTS idx_audit_created ON audit_logs(created_at); `) + + // 老库迁移:为已存在的表补充新增列(SQLite 不支持 ADD COLUMN IF NOT EXISTS) + ensureColumn(db, 'contacts', 'read', 'INTEGER NOT NULL DEFAULT 0') + ensureColumn(db, 'subscribers', 'token', 'TEXT') +} + +/** 若表中缺少某列则补上(用于老库升级) */ +function ensureColumn(db: Database.Database, table: string, column: string, ddl: string): void { + const cols = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }> + if (!cols.some((c) => c.name === column)) { + db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${ddl}`) + } } /** diff --git a/server/utils/password.ts b/server/utils/password.ts new file mode 100644 index 0000000..1999f1d --- /dev/null +++ b/server/utils/password.ts @@ -0,0 +1,26 @@ +import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto' +import { promisify } from 'node:util' + +/** + * 密码哈希/校验(scrypt,盐 + 哈希以冒号分隔存储)。 + * 独立于 Nuxt/Nitro 依赖,便于单元测试。 + */ +const scryptAsync = promisify(scrypt) as ( + password: string, + salt: string, + keylen: number, +) => Promise + +export async function hashPassword(password: string): Promise { + const salt = randomBytes(16).toString('hex') + const key = await scryptAsync(password, salt, 64) + return `${salt}:${key.toString('hex')}` +} + +export async function verifyPassword(password: string, stored: string): Promise { + const [salt, hash] = stored.split(':') + if (!salt || !hash) return false + const key = await scryptAsync(password, salt, 64) + const expected = Buffer.from(hash, 'hex') + return key.length === expected.length && timingSafeEqual(key, expected) +} diff --git a/tests/password.test.ts b/tests/password.test.ts new file mode 100644 index 0000000..7f244ec --- /dev/null +++ b/tests/password.test.ts @@ -0,0 +1,26 @@ +import { describe, it, expect } from 'vitest' +import { hashPassword, verifyPassword } from '../server/utils/password' + +describe('password hashing (scrypt)', () => { + it('hashes and verifies the correct password', async () => { + const hash = await hashPassword('secret123') + expect(hash).toContain(':') + expect(await verifyPassword('secret123', hash)).toBe(true) + }) + + it('rejects a wrong password', async () => { + const hash = await hashPassword('secret123') + expect(await verifyPassword('wrong-pass', hash)).toBe(false) + }) + + it('rejects a malformed stored hash', async () => { + expect(await verifyPassword('secret123', 'no-separator')).toBe(false) + expect(await verifyPassword('secret123', '')).toBe(false) + }) + + it('produces a unique salt per call', async () => { + const a = await hashPassword('secret123') + const b = await hashPassword('secret123') + expect(a).not.toBe(b) + }) +}) diff --git a/tests/seed.test.ts b/tests/seed.test.ts new file mode 100644 index 0000000..505d600 --- /dev/null +++ b/tests/seed.test.ts @@ -0,0 +1,45 @@ +import { describe, it, expect } from 'vitest' +import { articlesSeed, worksSeed } from '../server/utils/seed' + +describe('seed data integrity', () => { + it('has 6 articles and 6 works', () => { + expect(articlesSeed).toHaveLength(6) + expect(worksSeed).toHaveLength(6) + }) + + it('slugs are unique', () => { + const articleSlugs = articlesSeed.map((a) => a.slug) + expect(new Set(articleSlugs).size).toBe(articleSlugs.length) + const workSlugs = worksSeed.map((w) => w.slug) + expect(new Set(workSlugs).size).toBe(workSlugs.length) + }) + + it('bilingual fields are complete for articles', () => { + for (const a of articlesSeed) { + expect(a.slug).toBeTruthy() + expect(a.titleZh).toBeTruthy() + expect(a.titleEn).toBeTruthy() + expect(a.excerptZh).toBeTruthy() + expect(a.excerptEn).toBeTruthy() + expect(a.contentZh.length).toBeGreaterThan(0) + expect(a.contentEn.length).toBeGreaterThan(0) + expect(a.image).toBeTruthy() + expect(a.published).toBe(1) + } + }) + + it('bilingual fields are complete for works', () => { + for (const w of worksSeed) { + expect(w.slug).toBeTruthy() + expect(w.titleZh).toBeTruthy() + expect(w.titleEn).toBeTruthy() + expect(w.descriptionZh).toBeTruthy() + expect(w.descriptionEn).toBeTruthy() + expect(w.overviewZh).toBeTruthy() + expect(w.overviewEn).toBeTruthy() + expect(w.gallery.length).toBeGreaterThan(0) + expect(w.tags.length).toBeGreaterThan(0) + expect(w.published).toBe(1) + } + }) +}) diff --git a/tests/validateContent.test.ts b/tests/validateContent.test.ts new file mode 100644 index 0000000..fafcf8a --- /dev/null +++ b/tests/validateContent.test.ts @@ -0,0 +1,55 @@ +import { describe, it, expect } from 'vitest' +import { + isValidSlug, + isValidArticleCategory, + isValidWorkCategory, + normalizeBlocks, + normalizeTags, + normalizeGallery, +} from '../server/utils/validateContent' + +describe('content validation', () => { + it('validates slugs', () => { + expect(isValidSlug('design-trends-2026')).toBe(true) + expect(isValidSlug('a')).toBe(false) + expect(isValidSlug('')).toBe(false) + expect(isValidSlug('with space')).toBe(false) + expect(isValidSlug('UPPER')).toBe(false) + expect(isValidSlug('x'.repeat(65))).toBe(false) + }) + + it('validates article/work categories', () => { + expect(isValidArticleCategory('insights')).toBe(true) + expect(isValidArticleCategory('projects')).toBe(true) + expect(isValidArticleCategory('bogus')).toBe(false) + expect(isValidWorkCategory('webDesign')).toBe(true) + expect(isValidWorkCategory('development')).toBe(true) + expect(isValidWorkCategory('insights')).toBe(false) + }) + + it('normalizes content blocks (filters invalid)', () => { + const input = [ + { type: 'paragraph', text: 'hi' }, + { type: 'heading', text: 'title' }, + { type: 'quote', text: 'quote' }, + { type: 'image', text: 'https://x/a.png' }, + { type: 'bogus', text: 'x' }, + { text: 'no-type' }, + null, + 'string', + ] + expect(normalizeBlocks(input as never[])).toEqual([ + { type: 'paragraph', text: 'hi' }, + { type: 'heading', text: 'title' }, + { type: 'quote', text: 'quote' }, + { type: 'image', text: 'https://x/a.png' }, + ]) + expect(normalizeBlocks(undefined)).toEqual([]) + }) + + it('normalizes tags and gallery', () => { + expect(normalizeTags([' a ', 'b', '', 5])).toEqual(['a', 'b']) + expect(normalizeTags('not-array' as never)).toEqual([]) + expect(normalizeGallery(['/x.png', ' ', '/y.png'])).toEqual(['/x.png', '/y.png']) + }) +}) diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..9eef0e8 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + environment: 'node', + include: ['tests/**/*.test.ts'], + }, +}) From 5a7ad8de112ab67ae7aca86bc797eab58a1fddcb Mon Sep 17 00:00:00 2001 From: chenchun Date: Thu, 6 Aug 2026 18:40:17 +0800 Subject: [PATCH 04/12] =?UTF-8?q?feat:=20=E5=85=A8=E9=9D=A2=E5=8D=87?= =?UTF-8?q?=E7=BA=A7=E2=80=94=E2=80=94=E5=90=8E=E5=8F=B0=E4=BC=98=E5=8C=96?= =?UTF-8?q?=20/=20=E5=8A=A8=E6=80=81=E9=85=8D=E7=BD=AE=20/=20=E4=B8=AA?= =?UTF-8?q?=E4=BA=BA=E4=B8=AD=E5=BF=83=20/=20OSS=20=E5=AD=98=E5=82=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - OSS 文件存储(RustFS / S3 v4 兼容,零依赖手写 SigV4): 上传/列表/删除走桶 arcticnewone,/uploads 代理服务 + 本地回退; server/utils/sigv4.ts 纯函数 + AWS 测试向量验证 - 业务动态配置:settings 表 + /api/settings(公开) + /api/admin/settings(PATCH), useSiteSettings 组合式,footer/contact/tools/app.vue/侧边栏/工具页全部接入, 后台 /admin/settings 修改前台即时生效(站点/联系/社交/工具箱/页脚/SEO) - 后台全面优化:Admin* 设计系统(按钮/输入/表单/卡片/徽标/弹窗/确认/空态/骨架/ 分页/页头/Toast)14 组件;Dashboard 增强;各列表页搜索/筛选/批量删除/分页; 布局与侧边栏分组;统一 toast/确认反馈 - 个人中心全新重设计:顶部资料卡 + 统计、精致化改密/删号(二次确认)、 收藏封面网格、评论卡片、移动端适配 - deploy.sh 支持 OSS 凭据注入(NUXT_OSS_*);.env.example 更新 - 测试 17 例全过(含 SigV4 AWS 向量、settings 默认结构) --- .env.example | 9 + README.md | 19 +- app/app.vue | 28 +- app/components/admin/AdminBadge.vue | 22 + app/components/admin/AdminButton.vue | 40 + app/components/admin/AdminCard.vue | 16 + app/components/admin/AdminConfirm.vue | 27 + app/components/admin/AdminEmptyState.vue | 17 + app/components/admin/AdminInput.vue | 32 + app/components/admin/AdminModal.vue | 48 ++ app/components/admin/AdminPageHeader.vue | 13 + app/components/admin/AdminPagination.vue | 20 + app/components/admin/AdminSelect.vue | 25 + app/components/admin/AdminSidebar.vue | 87 +- app/components/admin/AdminSkeleton.vue | 11 + app/components/admin/AdminTextarea.vue | 31 + app/components/admin/AdminToast.vue | 54 ++ app/components/admin/AdminToggle.vue | 18 + app/components/layouts/ArcticNewOneFooter.vue | 26 +- app/composables/useSiteSettings.ts | 20 + app/config/site.ts | 130 ++- app/layouts/admin.vue | 11 +- app/pages/account.vue | 798 ++++++++++++------ app/pages/admin/audit.vue | 346 ++++---- app/pages/admin/comments.vue | 454 +++++----- app/pages/admin/contacts.vue | 432 ++++++---- app/pages/admin/news.vue | 489 +++++------ app/pages/admin/settings.vue | 260 ++++++ app/pages/admin/subscribers.vue | 385 ++++++--- app/pages/admin/uploads.vue | 282 ++++--- app/pages/admin/users.vue | 366 ++++---- app/pages/admin/work.vue | 673 +++++++-------- app/pages/contact.vue | 17 +- app/pages/tools.vue | 45 +- app/stores/toast.ts | 31 + deploy.sh | 6 + i18n/locales/en.json | 5 +- i18n/locales/zh.json | 5 +- nuxt.config.ts | 7 + server/api/admin/settings.get.ts | 10 + server/api/admin/settings.patch.ts | 44 + server/api/admin/upload.post.ts | 23 +- server/api/admin/uploads.delete.ts | 41 + server/api/admin/uploads.get.ts | 18 +- server/api/admin/uploads/[name].delete.ts | 28 - server/api/settings.get.ts | 8 + server/routes/feed.xml.ts | 6 +- server/routes/uploads/[...path].get.ts | 44 +- server/utils/config.ts | 17 + server/utils/db.ts | 6 + server/utils/s3.ts | 121 +++ server/utils/settings.ts | 45 + server/utils/sigv4.ts | 60 ++ tests/sigv4.test.ts | 44 + tests/siteSettings.test.ts | 30 + 55 files changed, 3857 insertions(+), 1993 deletions(-) create mode 100644 app/components/admin/AdminBadge.vue create mode 100644 app/components/admin/AdminButton.vue create mode 100644 app/components/admin/AdminCard.vue create mode 100644 app/components/admin/AdminConfirm.vue create mode 100644 app/components/admin/AdminEmptyState.vue create mode 100644 app/components/admin/AdminInput.vue create mode 100644 app/components/admin/AdminModal.vue create mode 100644 app/components/admin/AdminPageHeader.vue create mode 100644 app/components/admin/AdminPagination.vue create mode 100644 app/components/admin/AdminSelect.vue create mode 100644 app/components/admin/AdminSkeleton.vue create mode 100644 app/components/admin/AdminTextarea.vue create mode 100644 app/components/admin/AdminToast.vue create mode 100644 app/components/admin/AdminToggle.vue create mode 100644 app/composables/useSiteSettings.ts create mode 100644 app/pages/admin/settings.vue create mode 100644 app/stores/toast.ts create mode 100644 server/api/admin/settings.get.ts create mode 100644 server/api/admin/settings.patch.ts create mode 100644 server/api/admin/uploads.delete.ts delete mode 100644 server/api/admin/uploads/[name].delete.ts create mode 100644 server/api/settings.get.ts create mode 100644 server/utils/s3.ts create mode 100644 server/utils/settings.ts create mode 100644 server/utils/sigv4.ts create mode 100644 tests/sigv4.test.ts create mode 100644 tests/siteSettings.test.ts diff --git a/.env.example b/.env.example index 41dc9fa..a3432d5 100644 --- a/.env.example +++ b/.env.example @@ -30,3 +30,12 @@ NUXT_ADMIN_EMAILS=chenchun@virtheart.com # 预置管理员初始密码(仅首次初始化数据库时创建 admin 账号用;生产由 deploy.sh 注入) # NUXT_ADMIN_INITIAL_PASSWORD=change-me + +# ---- OSS 文件存储(RustFS / S3 v4 兼容;凭据不写入仓库,生产由 deploy.sh 注入 Secret)---- +NUXT_OSS_ENDPOINT=oss.virtheart.com +NUXT_OSS_ACCESS_KEY= +NUXT_OSS_SECRET_KEY= +NUXT_OSS_BUCKET=arcticnewone +NUXT_OSS_REGION=us-east-1 +# 若桶公开可读,可填 https://oss.virtheart.com/arcticnewone 用于直链;留空则走 /uploads 代理 +NUXT_OSS_PUBLIC_BASE= diff --git a/README.md b/README.md index 2ce12ca..19592c0 100644 --- a/README.md +++ b/README.md @@ -52,16 +52,16 @@ pnpm dev | 模块 | 说明 | | --- | --- | | 页面 | 首页、工作室、作品(列表/详情)、动态(列表/详情)、工具箱、联系、个人中心 | -| **后台管理** | `/admin`:Dashboard 统计、动态/作品增删改(中英双语 CMS)、用户管理、评论审核、联系/订阅管理、图片上传 | -| 用户系统 | 真实注册/登录/登出(scrypt 密码哈希 + httpOnly Cookie 会话);预置 admin 账号 | -| 个人中心 | `/account`:资料编辑、作品收藏、我的评论;管理员可进入 `/admin` | +| **后台管理** | `/admin`:Dashboard、动态/作品增删改(双语 CMS)、用户/评论/联系/订阅管理、图片管理(OSS)、操作审计日志、**站点动态配置** | +| **动态配置** | 站点信息/联系方式/社交链接/工具箱/页脚文案/SEO 均可在 `/admin/settings` 后台修改,前台即时生效 | +| **文件存储** | 图片上传/管理使用 OSS(RustFS,S3 v4 兼容,桶 `arcticnewone`),经 `/uploads` 代理服务 | +| 用户系统 | 注册/登录/登出、修改密码、自助删除账号、预置 admin;个人中心(资料/收藏/评论) | | 交互 | 作品收藏、新闻评论、分享(X/LinkedIn/复制链接)、搜索、加载更多 | -| 国际化 | 中/英双语,Header 一键切换(`no_prefix`,默认中文);内容双语存于数据库 | -| SEO | 动态 `sitemap.xml`(数据来自 DB)/ `robots.txt`、JSON-LD、自动生成的 `og-image.png` | -| 邮件 | SMTP 发送联系/订阅邮件;未配置 SMTP 时数据仍真实写入 SQLite | +| 国际化 | 中/英双语,Header 一键切换;内容双语存于数据库 | +| SEO | 动态 `sitemap.xml`/`robots.txt`/`feed.xml`(RSS)、JSON-LD、canonical、`og-image.png` | +| 工程 | `pnpm test`(vitest:密码/SigV4/校验器/种子/配置 17 例) | -> **预置管理员**:首次部署时若设置 `ADMIN_INITIAL_PASSWORD`(或由 `deploy.sh` 自动生成并打印), -> 数据库初始化会自动创建 `admin` 账号(邮箱取 `ADMIN_EMAILS` 第一个)。登录后访问 `/admin` 即可管理内容。 +> **预置管理员**:首次部署设置 `ADMIN_INITIAL_PASSWORD`(或由 `deploy.sh` 自动生成并打印)会自动创建 `admin` 账号,登录后访问 `/admin` 管理内容与配置。 ### 环境变量(详见 `.env.example`,Nuxt runtimeConfig 使用 `NUXT_` 前缀) @@ -74,8 +74,9 @@ pnpm dev | `NUXT_CONTACT_TO` | 联系表单留言收件邮箱 | | `NUXT_ADMIN_EMAILS` | 管理员邮箱(逗号分隔),命中者个人中心可见管理面板 | | `NUXT_ADMIN_INITIAL_PASSWORD` | 预置管理员初始密码(仅首次初始化创建 admin 账号用) | +| `NUXT_OSS_ENDPOINT/ACCESS_KEY/SECRET_KEY/BUCKET/REGION/PUBLIC_BASE` | OSS 文件存储(RustFS / S3 v4,凭据仅走 Secret,不写入仓库) | -> `deploy.sh` 中的对外变量名(`SESSION_SECRET`/`SMTP_*`/`CONTACT_TO`/`ADMIN_EMAILS`/`ADMIN_INITIAL_PASSWORD`)会在写入 K8s Secret 时自动加 `NUXT_` 前缀。 +> `deploy.sh` 中的对外变量名(`SESSION_SECRET`/`SMTP_*`/`CONTACT_TO`/`ADMIN_EMAILS`/`ADMIN_INITIAL_PASSWORD`/`OSS_*`)会在写入 K8s Secret 时自动加 `NUXT_` 前缀。 ## 项目结构 diff --git a/app/app.vue b/app/app.vue index 1bc7239..9d71d37 100755 --- a/app/app.vue +++ b/app/app.vue @@ -2,9 +2,10 @@ import { computed } from 'vue' import { useHead, useSeoMeta, useRuntimeConfig, useRoute } from '#imports' import { useI18n } from 'vue-i18n' -import { siteConfig } from '~/config/site' +import { useSiteSettings } from '~/composables/useSiteSettings' const { t } = useI18n() +const { settings, loc } = useSiteSettings() const { public: publicCfg } = useRuntimeConfig() const route = useRoute() const baseUrl = String(publicCfg.siteUrl || '').replace(/\/$/, '') @@ -15,40 +16,41 @@ const siteImage = baseUrl ? `${baseUrl}/og-image.png` : '/og-image.png' // 配置全局 Title 模板 + canonical(SEO) useHead({ titleTemplate: (titleChunk?: string) => { - const siteName = t('app.name') + const siteName = settings.value?.site.name || t('app.name') return titleChunk ? `${titleChunk} - ${siteName}` : siteName }, link: [ { rel: 'canonical', href: computed(() => (baseUrl ? `${baseUrl}${route.path}` : undefined)) }, ], - // JSON-LD 结构化数据(Organization) + // JSON-LD 结构化数据(Organization,取自后台动态配置) script: [ { type: 'application/ld+json', innerHTML: JSON.stringify({ '@context': 'https://schema.org', '@type': 'Organization', - name: t('app.name'), - alternateName: siteConfig.brandZh, - description: t('app.description'), + name: settings.value?.site.name || t('app.name'), + alternateName: settings.value?.site.brand || '', + description: loc(settings.value?.site.description) || t('app.description'), url: baseUrl || undefined, logo: siteImage, - sameAs: siteConfig.socials.map((s) => s.url), + sameAs: (settings.value?.socials ?? []).map((s) => s.url), }), }, ], }) -// 配置全局基础 SEO 和 Meta (响应式支持国际化) +// 配置全局基础 SEO 和 Meta (取自后台动态配置,响应式国际化) useSeoMeta({ - description: () => t('app.description'), - ogTitle: () => t('app.name'), - ogDescription: () => t('app.description'), + description: () => loc(settings.value?.site.description) || t('app.description'), + keywords: () => loc(settings.value?.seo.keywords) || undefined, + ogTitle: () => settings.value?.site.name || t('app.name'), + ogDescription: () => loc(settings.value?.site.description) || t('app.description'), ogImage: siteImage, ogType: 'website', twitterCard: 'summary_large_image', - twitterTitle: () => t('app.name'), - twitterDescription: () => t('app.description'), + twitterTitle: () => settings.value?.site.name || t('app.name'), + twitterDescription: () => loc(settings.value?.site.description) || t('app.description'), twitterImage: siteImage, }) diff --git a/app/components/admin/AdminBadge.vue b/app/components/admin/AdminBadge.vue new file mode 100644 index 0000000..1a4b540 --- /dev/null +++ b/app/components/admin/AdminBadge.vue @@ -0,0 +1,22 @@ + + + diff --git a/app/components/admin/AdminButton.vue b/app/components/admin/AdminButton.vue new file mode 100644 index 0000000..f71384a --- /dev/null +++ b/app/components/admin/AdminButton.vue @@ -0,0 +1,40 @@ + + + diff --git a/app/components/admin/AdminCard.vue b/app/components/admin/AdminCard.vue new file mode 100644 index 0000000..8c4528b --- /dev/null +++ b/app/components/admin/AdminCard.vue @@ -0,0 +1,16 @@ + + + diff --git a/app/components/admin/AdminConfirm.vue b/app/components/admin/AdminConfirm.vue new file mode 100644 index 0000000..e6f977c --- /dev/null +++ b/app/components/admin/AdminConfirm.vue @@ -0,0 +1,27 @@ + + + diff --git a/app/components/admin/AdminEmptyState.vue b/app/components/admin/AdminEmptyState.vue new file mode 100644 index 0000000..be1da50 --- /dev/null +++ b/app/components/admin/AdminEmptyState.vue @@ -0,0 +1,17 @@ + + + diff --git a/app/components/admin/AdminInput.vue b/app/components/admin/AdminInput.vue new file mode 100644 index 0000000..0dd329f --- /dev/null +++ b/app/components/admin/AdminInput.vue @@ -0,0 +1,32 @@ + + + diff --git a/app/components/admin/AdminModal.vue b/app/components/admin/AdminModal.vue new file mode 100644 index 0000000..2bc80b6 --- /dev/null +++ b/app/components/admin/AdminModal.vue @@ -0,0 +1,48 @@ + + + + + diff --git a/app/components/admin/AdminPageHeader.vue b/app/components/admin/AdminPageHeader.vue new file mode 100644 index 0000000..ce26a0f --- /dev/null +++ b/app/components/admin/AdminPageHeader.vue @@ -0,0 +1,13 @@ + + + diff --git a/app/components/admin/AdminPagination.vue b/app/components/admin/AdminPagination.vue new file mode 100644 index 0000000..7d914bf --- /dev/null +++ b/app/components/admin/AdminPagination.vue @@ -0,0 +1,20 @@ + + + diff --git a/app/components/admin/AdminSelect.vue b/app/components/admin/AdminSelect.vue new file mode 100644 index 0000000..f618b49 --- /dev/null +++ b/app/components/admin/AdminSelect.vue @@ -0,0 +1,25 @@ + + + diff --git a/app/components/admin/AdminSidebar.vue b/app/components/admin/AdminSidebar.vue index 115e062..5af8112 100644 --- a/app/components/admin/AdminSidebar.vue +++ b/app/components/admin/AdminSidebar.vue @@ -1,24 +1,52 @@ diff --git a/app/components/admin/AdminTextarea.vue b/app/components/admin/AdminTextarea.vue new file mode 100644 index 0000000..3d7916b --- /dev/null +++ b/app/components/admin/AdminTextarea.vue @@ -0,0 +1,31 @@ + - diff --git a/app/pages/admin/settings.vue b/app/pages/admin/settings.vue new file mode 100644 index 0000000..2d7963e --- /dev/null +++ b/app/pages/admin/settings.vue @@ -0,0 +1,260 @@ + + + diff --git a/app/pages/admin/subscribers.vue b/app/pages/admin/subscribers.vue index 1b406e7..a14217e 100644 --- a/app/pages/admin/subscribers.vue +++ b/app/pages/admin/subscribers.vue @@ -1,110 +1,13 @@ - - + + diff --git a/app/pages/admin/uploads.vue b/app/pages/admin/uploads.vue index 7900d33..b872637 100644 --- a/app/pages/admin/uploads.vue +++ b/app/pages/admin/uploads.vue @@ -1,95 +1,13 @@ - - + + diff --git a/app/pages/admin/users.vue b/app/pages/admin/users.vue index d6fa44f..325824a 100644 --- a/app/pages/admin/users.vue +++ b/app/pages/admin/users.vue @@ -1,129 +1,14 @@ - - + + diff --git a/app/pages/admin/work.vue b/app/pages/admin/work.vue index d96b27a..940bfdb 100644 --- a/app/pages/admin/work.vue +++ b/app/pages/admin/work.vue @@ -1,14 +1,14 @@ diff --git a/app/layouts/admin.vue b/app/layouts/admin.vue index 09443f8..5ab8a1b 100644 --- a/app/layouts/admin.vue +++ b/app/layouts/admin.vue @@ -18,7 +18,7 @@ const sidebarOpen = ref(false)
-
-
+
+
{
- +
@@ -192,12 +192,13 @@ const formatDate = (raw?: string) => {