Merge branch 'steelhead'
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
# 本地开发环境变量示例
|
||||
# 复制为 .env 后按需修改(.env 已被 .gitignore 忽略,不会提交)
|
||||
|
||||
# PostgreSQL 连接串(docker compose 起库后默认可用,宿主机端口 5433)
|
||||
NUXT_DATABASE_URL=postgres://arcticnewone:arcticnewone_dev_password@localhost:5433/arcticnewone
|
||||
|
||||
# JWT 签名密钥(生产环境务必改为随机长字符串)
|
||||
NUXT_JWT_SECRET=dev-only-secret-change-in-production
|
||||
|
||||
# SMTP 邮件通知(可选;不配置时联系表单/订阅仅入库)
|
||||
# NUXT_SMTP_HOST=smtp.example.com
|
||||
# NUXT_SMTP_PORT=465
|
||||
# NUXT_SMTP_USER=your-smtp-user
|
||||
# NUXT_SMTP_PASS=your-smtp-password
|
||||
# NUXT_SMTP_FROM=北极新一 <noreply@virtheart.com>
|
||||
# NUXT_SMTP_CONTACT_TO=chenchun@virtheart.com
|
||||
@@ -4,21 +4,35 @@
|
||||
|
||||
## 技术栈
|
||||
|
||||
- [Nuxt 4](https://nuxt.com/) — 应用框架(服务端渲染 + 静态生成)
|
||||
- [Nuxt 4](https://nuxt.com/) — 应用框架(服务端渲染 + 内置 Nitro Server 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/) — 国际化(中/英双语)
|
||||
- [@nuxt/icon](https://nuxt.com/modules/icon) — 图标
|
||||
- [PostgreSQL](https://www.postgresql.org/) — 数据库(用户 / 联系留言 / 资讯订阅)
|
||||
- [node-postgres (pg)](https://node-postgres.com/) — 数据库驱动
|
||||
- [jose](https://github.com/panva/jose) — JWT 会话(httpOnly Cookie)
|
||||
- [bcryptjs](https://github.com/dcodeIO/bcryptjs) — 密码哈希
|
||||
- [nodemailer](https://nodemailer.com/) — SMTP 邮件通知(可选)
|
||||
- [pnpm](https://pnpm.io/) — 包管理器
|
||||
|
||||
## 功能
|
||||
|
||||
- 展示型页面:首页、工作室、作品集、动态资讯、工具箱、联系
|
||||
- 用户系统:注册 / 登录 / 登出(JWT + httpOnly Cookie,密码 bcrypt 哈希)
|
||||
- 联系表单:留言入库 PostgreSQL,可选 SMTP 邮件通知
|
||||
- 资讯订阅:邮箱订阅入库(唯一约束防重复),可选 SMTP 通知
|
||||
- 国际化:中/英双语,默认中文
|
||||
|
||||
## 本地开发
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Node.js ≥ 20(推荐 22,与 Docker 构建镜像一致)
|
||||
- pnpm ≥ 9
|
||||
- Docker(用于本地 PostgreSQL,或自行提供 PostgreSQL 16+)
|
||||
|
||||
### 安装与启动
|
||||
|
||||
@@ -26,7 +40,13 @@
|
||||
# 1. 安装依赖
|
||||
pnpm install
|
||||
|
||||
# 2. 启动开发服务器(默认 http://localhost:3000)
|
||||
# 2. 启动本地数据库(PostgreSQL 16,映射宿主机 5433 端口)
|
||||
docker compose up -d postgres
|
||||
|
||||
# 3. 配置环境变量(可写入 .env 文件,已被 .gitignore 忽略)
|
||||
cp .env.example .env
|
||||
|
||||
# 4. 启动开发服务器(默认 http://localhost:3000)
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
@@ -38,10 +58,43 @@ pnpm dev
|
||||
| --- | --- |
|
||||
| `pnpm dev` | 启动开发服务器 |
|
||||
| `pnpm build` | 构建生产版本(生成 `.output/`) |
|
||||
| `pnpm generate` | 静态站点生成(输出到 `dist/`) |
|
||||
| `pnpm generate` | 静态站点生成(输出到 `dist/`,注意:Server API 需要 Node 运行时不支持静态生成) |
|
||||
| `pnpm preview` | 本地预览生产构建 |
|
||||
| `pnpm start` | 以 Node 方式启动 `.output/server/index.mjs` |
|
||||
|
||||
## 环境变量
|
||||
|
||||
所有变量均可通过 `.env` 文件或系统环境变量注入,Nuxt 自动读取 `NUXT_*` 前缀:
|
||||
|
||||
| 变量 | 必填 | 默认值 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `NUXT_DATABASE_URL` | ✅ | — | PostgreSQL 连接串,如 `postgres://user:pass@localhost:5433/arcticnewone` |
|
||||
| `NUXT_JWT_SECRET` | ✅(生产) | 开发默认值 | JWT 签名密钥,生产必须设置为随机长字符串(`openssl rand -hex 32`) |
|
||||
| `NUXT_SMTP_HOST` | 否 | — | SMTP 服务器地址(配置后联系表单/订阅会发邮件通知) |
|
||||
| `NUXT_SMTP_PORT` | 否 | 465 | SMTP 端口 |
|
||||
| `NUXT_SMTP_USER` | 否 | — | SMTP 用户名 |
|
||||
| `NUXT_SMTP_PASS` | 否 | — | SMTP 密码 |
|
||||
| `NUXT_SMTP_FROM` | 否 | — | 发件人,如 `北极新一 <noreply@virtheart.com>` |
|
||||
| `NUXT_SMTP_CONTACT_TO` | 否 | SMTP_USER | 收件人(联系表单与订阅通知发往此邮箱) |
|
||||
| `POSTGRES_PASSWORD` | 仅 compose | `arcticnewone_dev_password` | docker-compose 中数据库密码(本地开发) |
|
||||
|
||||
SMTP 未配置时,联系表单与订阅**仍然正常入库**,只是不发送邮件通知。
|
||||
|
||||
## Server API
|
||||
|
||||
项目内置 Nitro Server API(`server/` 目录),应用启动时自动建表(幂等):
|
||||
|
||||
| 接口 | 方法 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `/api/auth/register` | POST | 注册(用户名/邮箱唯一校验,成功即自动登录) |
|
||||
| `/api/auth/login` | POST | 登录(支持用户名/邮箱/手机号 + 密码) |
|
||||
| `/api/auth/logout` | POST | 登出(清除 Cookie) |
|
||||
| `/api/auth/me` | GET | 从 Cookie 恢复当前用户 |
|
||||
| `/api/contact` | POST | 提交联系表单(入库 + 可选邮件通知) |
|
||||
| `/api/newsletter/subscribe` | POST | 邮箱订阅资讯(入库,重复订阅返回 409) |
|
||||
|
||||
错误响应统一返回 `{ statusMessage: '<i18n错误码>' }`,前端按错误码显示对应语言的文案。
|
||||
|
||||
## 项目结构
|
||||
|
||||
```text
|
||||
@@ -49,20 +102,25 @@ pnpm dev
|
||||
├── app/ # 应用源码(Nuxt 4 约定目录)
|
||||
│ ├── app.vue # 应用入口(全局 SEO / Meta)
|
||||
│ ├── assets/ # 静态资源(样式、图片等)
|
||||
│ ├── components/ # 组件(common / home)
|
||||
│ ├── components/ # 组件(common / home / layouts)
|
||||
│ ├── composables/ # 组合式函数
|
||||
│ ├── layouts/ # 布局
|
||||
│ ├── pages/ # 页面(首页、工作室、作品、动态、工具、联系)
|
||||
│ ├── plugins/ # 插件(如 Lenis 平滑滚动)
|
||||
│ ├── stores/ # Pinia 状态
|
||||
│ ├── stores/ # Pinia 状态(user / app)
|
||||
│ └── types/ # 类型定义
|
||||
├── server/ # Nitro Server API(后端)
|
||||
│ ├── api/ # 接口(auth / contact / newsletter)
|
||||
│ ├── db/ # PostgreSQL 连接池 + Schema
|
||||
│ ├── plugins/ # 启动插件(自动建表)
|
||||
│ └── utils/ # JWT 认证、校验、邮件工具
|
||||
├── 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 等)
|
||||
├── deploy/ # 生产部署配置(Kubernetes Deployment/Service/Ingress/PostgreSQL)
|
||||
├── docker-compose.yml # 本地容器编排(应用 + PostgreSQL)
|
||||
├── nuxt.config.ts # Nuxt 配置(模块、i18n、runtimeConfig 等)
|
||||
├── tailwind.config.js # Tailwind 配置
|
||||
└── package.json # 项目依赖与脚本
|
||||
```
|
||||
@@ -80,15 +138,15 @@ pnpm dev
|
||||
|
||||
Dockerfile 基础镜像使用国内可访问的 DaoCloud 镜像源(`docker.m.daocloud.io/library/node:22-alpine`,Docker Hub 在国内不可达)。
|
||||
|
||||
本地启动(使用 SWR 镜像,与生产一致):
|
||||
本地一键启动(应用 + PostgreSQL,与生产一致):
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
生产部署使用 `deploy/` 目录下的 Kubernetes 配置(Deployment / Service / Ingress),
|
||||
生产部署使用 `deploy/` 目录下的 Kubernetes 配置(Deployment / Service / Ingress / 可选 PostgreSQL),
|
||||
镜像统一推送到华为云 SWR(`swr.cn-north-4.myhuaweicloud.com/virtheart/arcticnewone:latest`),
|
||||
部署与回滚步骤见 [deploy/README.md](deploy/README.md)。
|
||||
部署、Secret 创建与回滚步骤见 [deploy/README.md](deploy/README.md)。
|
||||
|
||||
## 国际化(i18n)
|
||||
|
||||
@@ -97,6 +155,7 @@ docker compose up -d
|
||||
- 语言文件位于 `i18n/locales/`:`zh.json`(中文)、`en.json`(英文)
|
||||
- 默认语言为中文(`defaultLocale: 'zh'`),URL 不包含语言前缀(`strategy: 'no_prefix'`),不自动探测浏览器语言
|
||||
- 组件中通过 `useI18n()` 的 `t()` 方法读取文案,例如 `t('nav.home')`
|
||||
- 服务端错误码与文案键一一对应(如 `auth.emailTaken`),新增接口错误时需同步添加中英文键
|
||||
|
||||
新增文案时,在 `zh.json` 和 `en.json` 中同步添加对应键即可。
|
||||
|
||||
|
||||
@@ -75,11 +75,6 @@
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<!-- 提示信息 -->
|
||||
<p class="mt-6 text-center text-sm text-gray-500">
|
||||
{{ t('auth.demoHint') }}
|
||||
</p>
|
||||
|
||||
<!-- 注册账号链接 -->
|
||||
<p class="mt-4 text-center text-sm text-gray-600">
|
||||
{{ t('auth.noAccount') }}
|
||||
@@ -146,7 +141,7 @@ const handleLogin = async () => {
|
||||
password.value = ''
|
||||
closeModal()
|
||||
} else {
|
||||
errorMessage.value = t('auth.loginError')
|
||||
errorMessage.value = t(result.error)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Login error:', error)
|
||||
|
||||
@@ -222,7 +222,7 @@ const handleRegister = async () => {
|
||||
closeModal()
|
||||
}, 2000)
|
||||
} else {
|
||||
errorMessage.value = result.error || t('auth.registerError')
|
||||
errorMessage.value = t(result.error)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Register error:', error)
|
||||
|
||||
@@ -13,6 +13,7 @@ const footerRef = ref<HTMLElement | null>(null)
|
||||
const newsletterEmail = ref('')
|
||||
const isSubscribing = ref(false)
|
||||
const subscribeStatus = ref<'idle' | 'success' | 'error'>('idle')
|
||||
const newsletterMessage = ref('')
|
||||
let ctx: gsap.Context
|
||||
|
||||
const pagesLinks = [
|
||||
@@ -33,39 +34,45 @@ const handleNewsletterSubmit = async () => {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
if (!emailRegex.test(newsletterEmail.value)) {
|
||||
subscribeStatus.value = 'error'
|
||||
newsletterMessage.value = t('footer.newsletterInvalidEmail')
|
||||
setTimeout(() => {
|
||||
subscribeStatus.value = 'idle'
|
||||
newsletterMessage.value = ''
|
||||
}, 3000)
|
||||
return
|
||||
}
|
||||
|
||||
isSubscribing.value = true
|
||||
subscribeStatus.value = 'idle'
|
||||
newsletterMessage.value = ''
|
||||
|
||||
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)
|
||||
// 真实订阅:入库(PostgreSQL,邮箱唯一)+ 可选 SMTP 通知
|
||||
await $fetch('/api/newsletter/subscribe', {
|
||||
method: 'POST',
|
||||
body: { email: newsletterEmail.value },
|
||||
})
|
||||
|
||||
subscribeStatus.value = 'success'
|
||||
newsletterMessage.value = t('footer.newsletterSuccess')
|
||||
newsletterEmail.value = ''
|
||||
|
||||
// 3秒后重置状态
|
||||
setTimeout(() => {
|
||||
subscribeStatus.value = 'idle'
|
||||
newsletterMessage.value = ''
|
||||
}, 3000)
|
||||
|
||||
} catch (error) {
|
||||
} catch (error: any) {
|
||||
console.error('Newsletter subscription error:', error)
|
||||
subscribeStatus.value = 'error'
|
||||
// 服务端错误码(如已订阅 409)优先展示
|
||||
const code = error?.data?.statusMessage || error?.statusMessage || ''
|
||||
newsletterMessage.value = code && code !== 'Bad Request' ? t(code) : t('footer.newsletterError')
|
||||
|
||||
setTimeout(() => {
|
||||
subscribeStatus.value = 'idle'
|
||||
newsletterMessage.value = ''
|
||||
}, 3000)
|
||||
} finally {
|
||||
isSubscribing.value = false
|
||||
@@ -183,6 +190,15 @@ onUnmounted(() => {
|
||||
<span class="w-1.5 h-1.5 bg-white rounded-full inline-block shrink-0"></span>
|
||||
{{ t('footer.newsletterNote') }}
|
||||
</div>
|
||||
|
||||
<!-- 订阅状态消息 -->
|
||||
<p
|
||||
v-if="newsletterMessage"
|
||||
class="mt-3 text-xs animated-item"
|
||||
:class="subscribeStatus === 'success' ? 'text-green-400' : 'text-red-400'"
|
||||
>
|
||||
{{ newsletterMessage }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="mt-24 lg:mt-0 flex items-center gap-2 animated-item">
|
||||
|
||||
@@ -386,11 +386,11 @@ if (typeof window !== 'undefined') {
|
||||
class="flex items-center gap-3 px-4 py-2 rounded-full hover:bg-gray-100 transition-all duration-300"
|
||||
>
|
||||
<img
|
||||
:src="userStore.user?.avatar"
|
||||
:alt="userStore.user?.name"
|
||||
:src="userStore.avatar"
|
||||
:alt="userStore.user?.username"
|
||||
class="w-9 h-9 rounded-full object-cover border-2 border-gray-200"
|
||||
/>
|
||||
<span class="text-sm font-semibold text-black">{{ userStore.user?.name }}</span>
|
||||
<span class="text-sm font-semibold text-black">{{ userStore.user?.username }}</span>
|
||||
<Icon
|
||||
name="ph:caret-down"
|
||||
class="w-4 h-4 text-gray-600 transition-transform duration-300"
|
||||
@@ -406,7 +406,7 @@ if (typeof window !== 'undefined') {
|
||||
@click="closeUserMenu"
|
||||
>
|
||||
<div class="px-4 py-3 border-b border-gray-100">
|
||||
<p class="text-sm font-semibold text-black">{{ userStore.user?.name }}</p>
|
||||
<p class="text-sm font-semibold text-black">{{ userStore.user?.username }}</p>
|
||||
<p class="text-xs text-gray-500 truncate">{{ userStore.user?.email }}</p>
|
||||
</div>
|
||||
<button
|
||||
@@ -471,12 +471,12 @@ if (typeof window !== 'undefined') {
|
||||
<div v-else class="flex flex-col items-center gap-4">
|
||||
<div class="flex items-center gap-3">
|
||||
<img
|
||||
:src="userStore.user?.avatar"
|
||||
:alt="userStore.user?.name"
|
||||
:src="userStore.avatar"
|
||||
:alt="userStore.user?.username"
|
||||
class="w-12 h-12 rounded-full object-cover border-2 border-gray-200"
|
||||
/>
|
||||
<div class="text-left">
|
||||
<p class="text-lg font-bold text-black">{{ userStore.user?.name }}</p>
|
||||
<p class="text-lg font-bold text-black">{{ userStore.user?.username }}</p>
|
||||
<p class="text-sm text-gray-500">{{ userStore.user?.email }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+10
-13
@@ -234,19 +234,14 @@ 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)
|
||||
// 真实提交:入库(PostgreSQL)+ 可选 SMTP 邮件通知
|
||||
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.'
|
||||
statusMessage.value = t('contact.form.successMessage')
|
||||
|
||||
// 清空表单
|
||||
Object.keys(form).forEach(key => {
|
||||
@@ -259,10 +254,12 @@ const handleSubmit = async () => {
|
||||
statusMessage.value = ''
|
||||
}, 3000)
|
||||
|
||||
} catch (error) {
|
||||
} catch (error: any) {
|
||||
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.'
|
||||
// 优先显示服务端返回的具体错误码(i18n key),否则显示通用错误
|
||||
const code = error?.data?.statusMessage || error?.statusMessage || ''
|
||||
statusMessage.value = code && code !== 'Bad Request' ? t(code) : t('contact.form.errorMessage')
|
||||
} finally {
|
||||
isSubmitting.value = false
|
||||
}
|
||||
|
||||
+56
-88
@@ -2,117 +2,85 @@ import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
export interface User {
|
||||
id: string
|
||||
name: string
|
||||
id: number
|
||||
username: string
|
||||
email: string
|
||||
avatar?: string
|
||||
phone?: string
|
||||
avatarUrl?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 从服务端错误响应中提取 i18n 错误码(如 'auth.emailTaken')
|
||||
*/
|
||||
function extractErrorCode(err: any): string {
|
||||
return err?.data?.statusMessage || err?.statusMessage || ''
|
||||
}
|
||||
|
||||
export const useUserStore = defineStore('user', () => {
|
||||
const user = ref<User | null>(null)
|
||||
const isAuthenticated = computed(() => user.value !== null)
|
||||
|
||||
// 登录
|
||||
// 登录(服务端校验账号密码,成功后写入 httpOnly Cookie)
|
||||
const login = async (account: string, password: string) => {
|
||||
try {
|
||||
// 模拟 API 调用 - 你需要替换为真实的登录 API
|
||||
// const response = await $fetch('/api/auth/login', {
|
||||
// method: 'POST',
|
||||
// body: { account, password }
|
||||
// })
|
||||
|
||||
// 模拟延迟
|
||||
await new Promise(resolve => setTimeout(resolve, 1000))
|
||||
|
||||
// 判断账号类型并提取用户名
|
||||
let username = account
|
||||
if (account.includes('@')) {
|
||||
// 邮箱:使用 @ 前面的部分
|
||||
username = account.split('@')[0]
|
||||
} else if (/^1[3-9]\d{9}$/.test(account)) {
|
||||
// 手机号:使用后4位
|
||||
username = 'User_' + account.slice(-4)
|
||||
}
|
||||
// 其他情况:直接使用账号作为用户名
|
||||
|
||||
// 模拟成功登录
|
||||
user.value = {
|
||||
id: '1',
|
||||
name: username,
|
||||
email: account.includes('@') ? account : `${account}@example.com`,
|
||||
avatar: `https://ui-avatars.com/api/?name=${encodeURIComponent(username)}&background=000&color=fff&size=128`
|
||||
}
|
||||
|
||||
// 保存到 localStorage
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('user', JSON.stringify(user.value))
|
||||
}
|
||||
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error('Login error:', error)
|
||||
return { success: false, error: 'Login failed' }
|
||||
const data = await $fetch<{ success: true; user: User }>('/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: { account, password },
|
||||
})
|
||||
user.value = data.user
|
||||
return { success: true as const }
|
||||
} catch (err) {
|
||||
const code = extractErrorCode(err)
|
||||
return { success: false as const, error: code || 'auth.loginError' }
|
||||
}
|
||||
}
|
||||
|
||||
// 登出
|
||||
const logout = () => {
|
||||
user.value = null
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.removeItem('user')
|
||||
}
|
||||
}
|
||||
|
||||
// 注册
|
||||
// 注册(成功后自动登录)
|
||||
const register = async (data: { username: string; email: string; phone?: string; password: string }) => {
|
||||
try {
|
||||
// 模拟 API 调用 - 你需要替换为真实的注册 API
|
||||
// const response = await $fetch('/api/auth/register', {
|
||||
// method: 'POST',
|
||||
// body: data
|
||||
// })
|
||||
|
||||
// 模拟延迟
|
||||
await new Promise(resolve => setTimeout(resolve, 1000))
|
||||
|
||||
// 模拟成功注册并自动登录
|
||||
user.value = {
|
||||
id: Date.now().toString(),
|
||||
name: data.username,
|
||||
email: data.email,
|
||||
avatar: `https://ui-avatars.com/api/?name=${encodeURIComponent(data.username)}&background=000&color=fff&size=128`
|
||||
}
|
||||
|
||||
// 保存到 localStorage
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('user', JSON.stringify(user.value))
|
||||
}
|
||||
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error('Register error:', error)
|
||||
return { success: false, error: 'Registration failed' }
|
||||
const res = await $fetch<{ success: true; user: User }>('/api/auth/register', {
|
||||
method: 'POST',
|
||||
body: data,
|
||||
})
|
||||
user.value = res.user
|
||||
return { success: true as const }
|
||||
} catch (err) {
|
||||
const code = extractErrorCode(err)
|
||||
return { success: false as const, error: code || 'auth.registerError' }
|
||||
}
|
||||
}
|
||||
|
||||
// 从 localStorage 恢复用户状态
|
||||
const restoreUser = () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
const savedUser = localStorage.getItem('user')
|
||||
if (savedUser) {
|
||||
try {
|
||||
user.value = JSON.parse(savedUser)
|
||||
} catch (error) {
|
||||
console.error('Failed to restore user:', error)
|
||||
localStorage.removeItem('user')
|
||||
}
|
||||
}
|
||||
// 登出(清除服务端 Cookie)
|
||||
const logout = async () => {
|
||||
try {
|
||||
await $fetch('/api/auth/logout', { method: 'POST' })
|
||||
} catch {
|
||||
// 忽略登出接口异常,本地状态照常清理
|
||||
}
|
||||
user.value = null
|
||||
}
|
||||
|
||||
// 从 httpOnly Cookie 恢复登录状态(替代旧的 localStorage 假恢复)
|
||||
const restoreUser = async () => {
|
||||
try {
|
||||
const data = await $fetch<{ user: User | null }>('/api/auth/me')
|
||||
user.value = data.user
|
||||
} catch {
|
||||
user.value = null
|
||||
}
|
||||
}
|
||||
|
||||
// 头像兜底:无自定义头像时用 ui-avatars 生成(保持与旧版一致的视觉)
|
||||
const avatar = computed(() => {
|
||||
if (user.value?.avatarUrl) return user.value.avatarUrl
|
||||
const name = user.value?.username || 'U'
|
||||
return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=000&color=fff&size=128`
|
||||
})
|
||||
|
||||
return {
|
||||
user,
|
||||
isAuthenticated,
|
||||
avatar,
|
||||
login,
|
||||
logout,
|
||||
register,
|
||||
|
||||
+38
-1
@@ -7,9 +7,10 @@
|
||||
| 文件 | 说明 |
|
||||
| --- | --- |
|
||||
| `namespace.yaml` | Namespace:项目专属命名空间 `arcticnewone` |
|
||||
| `deployment.yaml` | Deployment:SWR 镜像、副本数 1、私有镜像拉取 secrets |
|
||||
| `deployment.yaml` | Deployment:SWR 镜像、副本数 1、私有镜像拉取 secrets、数据库/SMTP 环境变量 |
|
||||
| `service.yaml` | Service:ClusterIP,80 端口转发到容器 3000 端口 |
|
||||
| `ingress.yaml` | Ingress:域名 `personal.virtheart.com`,Traefik + cert-manager 自动签发证书 |
|
||||
| `postgres.yaml` | (可选)集群内 PostgreSQL StatefulSet + PVC,仅在没有外部数据库时使用 |
|
||||
|
||||
`namespace.yaml` 负责创建 `arcticnewone` 命名空间;deployment/service/ingress 三个 YAML 的 `metadata` 均已指定 `namespace: arcticnewone`。
|
||||
|
||||
@@ -32,6 +33,24 @@ export SWR_PASSWORD="<密码>"
|
||||
|
||||
说明:脚本通过 `--output "type=image,push=true,oci-mediatypes=false"` 一步完成多架构构建推送,使用 Docker V2 manifest 格式(而非 OCI 格式,这是 SWR 兼容的关键),并禁用 provenance/SBOM(`--provenance=false --sbom=false`),保证 SWR 可正常解析。
|
||||
|
||||
## 数据库(PostgreSQL)
|
||||
|
||||
应用依赖 PostgreSQL 16+ 存储用户、联系留言与订阅数据。两种方式二选一:
|
||||
|
||||
### 方式 A:使用云托管数据库(推荐)
|
||||
|
||||
使用华为云 RDS for PostgreSQL 等托管服务(自带备份与高可用),创建数据库 `arcticnewone`,连接串格式:
|
||||
`postgres://<用户>:<密码>@<主机>:<端口>/arcticnewone`
|
||||
|
||||
### 方式 B:集群内部署(deploy/postgres.yaml)
|
||||
|
||||
```bash
|
||||
kubectl apply -f deploy/postgres.yaml
|
||||
```
|
||||
|
||||
会创建一个 StatefulSet + PVC(8Gi),数据库地址为 `arcticnewone-postgres.arcticnewone.svc.cluster.local:5432`。
|
||||
仅建议在测试/低负载场景使用;数据持久化依赖集群存储类。
|
||||
|
||||
## 部署前置条件
|
||||
|
||||
1. 镜像已构建并推送到华为云 SWR(通过项目根目录 `./build-and-push.sh` 执行,见上方「镜像构建与推送」)
|
||||
@@ -47,6 +66,22 @@ export SWR_PASSWORD="<密码>"
|
||||
--dry-run=client -o yaml | kubectl apply -f -
|
||||
```
|
||||
|
||||
5. 创建应用配置 Secret `arcticnewone-secrets`(`database-url` 与 `jwt-secret` 必填;SMTP 项可选,不配置时联系表单/订阅仅入库不发邮件):
|
||||
|
||||
```bash
|
||||
kubectl create secret generic arcticnewone-secrets -n arcticnewone \
|
||||
--from-literal=database-url='postgres://arcticnewone:<密码>@<数据库地址>:5432/arcticnewone' \
|
||||
--from-literal=jwt-secret='<随机长字符串,建议 openssl rand -hex 32>' \
|
||||
--from-literal=postgres-password='<集群内数据库密码,仅方式 B 需要>' \
|
||||
--from-literal=smtp-host='smtp.example.com' \
|
||||
--from-literal=smtp-port='465' \
|
||||
--from-literal=smtp-user='<SMTP 用户名>' \
|
||||
--from-literal=smtp-pass='<SMTP 密码>' \
|
||||
--from-literal=smtp-from='北极新一 <noreply@virtheart.com>' \
|
||||
--from-literal=smtp-contact-to='chenchun@virtheart.com' \
|
||||
--dry-run=client -o yaml | kubectl apply -f -
|
||||
```
|
||||
|
||||
## 部署步骤
|
||||
|
||||
```bash
|
||||
@@ -57,12 +92,14 @@ kubectl apply -f deploy/ingress.yaml
|
||||
```
|
||||
|
||||
`namespace.yaml` 需最先应用;其余三个 YAML 自带 `namespace: arcticnewone`,`kubectl apply` 时无需额外指定。
|
||||
若使用集群内数据库,还需先应用 `deploy/postgres.yaml`。
|
||||
|
||||
部署后验证:
|
||||
|
||||
```bash
|
||||
kubectl get deploy,svc,ingress -n arcticnewone
|
||||
kubectl rollout status deployment/arcticnewone -n arcticnewone
|
||||
kubectl logs deploy/arcticnewone -n arcticnewone | grep '\[db\]' # 确认数据库连接成功
|
||||
curl -I https://personal.virtheart.com
|
||||
```
|
||||
|
||||
|
||||
@@ -46,6 +46,55 @@ spec:
|
||||
value: "0.0.0.0"
|
||||
- name: PORT
|
||||
value: "3000"
|
||||
# 数据库连接(必填)
|
||||
- name: NUXT_DATABASE_URL
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: arcticnewone-secrets
|
||||
key: database-url
|
||||
# JWT 签名密钥(必填)
|
||||
- name: NUXT_JWT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: arcticnewone-secrets
|
||||
key: jwt-secret
|
||||
# SMTP 邮件通知(可选;不配置时表单/订阅仅入库)
|
||||
- name: NUXT_SMTP_HOST
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: arcticnewone-secrets
|
||||
key: smtp-host
|
||||
optional: true
|
||||
- name: NUXT_SMTP_PORT
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: arcticnewone-secrets
|
||||
key: smtp-port
|
||||
optional: true
|
||||
- name: NUXT_SMTP_USER
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: arcticnewone-secrets
|
||||
key: smtp-user
|
||||
optional: true
|
||||
- name: NUXT_SMTP_PASS
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: arcticnewone-secrets
|
||||
key: smtp-pass
|
||||
optional: true
|
||||
- name: NUXT_SMTP_FROM
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: arcticnewone-secrets
|
||||
key: smtp-from
|
||||
optional: true
|
||||
- name: NUXT_SMTP_CONTACT_TO
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: arcticnewone-secrets
|
||||
key: smtp-contact-to
|
||||
optional: true
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# =========================================================
|
||||
# Arcticnewone 可选生产数据库 - PostgreSQL StatefulSet
|
||||
#
|
||||
# 说明:
|
||||
# - 仅当生产环境没有可用的 PostgreSQL(如华为云 RDS)时才使用本文件
|
||||
# - 建议优先使用云托管数据库(RDS),自带备份/高可用,运维成本更低
|
||||
# - 数据保存在 PVC(8Gi 本地存储类),如需扩容请先调整 storage
|
||||
# - 部署后创建 Secret 提供连接信息(见 deploy/README.md)
|
||||
# =========================================================
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: arcticnewone-postgres
|
||||
namespace: arcticnewone
|
||||
labels:
|
||||
app: arcticnewone-postgres
|
||||
spec:
|
||||
clusterIP: None
|
||||
ports:
|
||||
- name: postgres
|
||||
port: 5432
|
||||
targetPort: 5432
|
||||
selector:
|
||||
app: arcticnewone-postgres
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: arcticnewone-postgres
|
||||
namespace: arcticnewone
|
||||
labels:
|
||||
app: arcticnewone-postgres
|
||||
spec:
|
||||
serviceName: arcticnewone-postgres
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: arcticnewone-postgres
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: arcticnewone-postgres
|
||||
spec:
|
||||
containers:
|
||||
- name: postgres
|
||||
image: docker.m.daocloud.io/library/postgres:16-alpine
|
||||
ports:
|
||||
- name: postgres
|
||||
containerPort: 5432
|
||||
env:
|
||||
- name: POSTGRES_DB
|
||||
value: "arcticnewone"
|
||||
- name: POSTGRES_USER
|
||||
value: "arcticnewone"
|
||||
- name: POSTGRES_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: arcticnewone-secrets
|
||||
key: postgres-password
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /var/lib/postgresql/data
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 256Mi
|
||||
limits:
|
||||
cpu: 500m
|
||||
memory: 1Gi
|
||||
readinessProbe:
|
||||
exec:
|
||||
command: ["pg_isready", "-U", "arcticnewone", "-d", "arcticnewone"]
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
livenessProbe:
|
||||
exec:
|
||||
command: ["pg_isready", "-U", "arcticnewone", "-d", "arcticnewone"]
|
||||
initialDelaySeconds: 15
|
||||
periodSeconds: 20
|
||||
volumeClaimTemplates:
|
||||
- metadata:
|
||||
name: data
|
||||
spec:
|
||||
accessModes: ["ReadWriteOnce"]
|
||||
resources:
|
||||
requests:
|
||||
storage: 8Gi
|
||||
@@ -1,4 +1,24 @@
|
||||
services:
|
||||
postgres:
|
||||
# 国内可访问的 DaoCloud 镜像源(与 Dockerfile 一致)
|
||||
image: docker.m.daocloud.io/library/postgres:16-alpine
|
||||
container_name: arcticnewone-postgres
|
||||
environment:
|
||||
POSTGRES_DB: arcticnewone
|
||||
POSTGRES_USER: arcticnewone
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-arcticnewone_dev_password}
|
||||
ports:
|
||||
# 宿主机 5433,避免与本机已有 PostgreSQL(5432/15432) 冲突
|
||||
- "5433:5432"
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U arcticnewone -d arcticnewone"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
|
||||
app:
|
||||
# 生产与本地使用同一 SWR 镜像(团队规范)
|
||||
image: swr.cn-north-4.myhuaweicloud.com/virtheart/arcticnewone:latest
|
||||
@@ -9,4 +29,21 @@ services:
|
||||
- NODE_ENV=production
|
||||
- HOST=0.0.0.0
|
||||
- PORT=3000
|
||||
# 数据库连接(compose 内通过服务名 postgres 访问)
|
||||
- NUXT_DATABASE_URL=postgres://arcticnewone:${POSTGRES_PASSWORD:-arcticnewone_dev_password}@postgres:5432/arcticnewone
|
||||
# JWT 签名密钥(生产必须覆盖)
|
||||
- NUXT_JWT_SECRET=${JWT_SECRET:-dev-only-secret-change-in-production}
|
||||
# SMTP 邮件通知(可选;不配置时表单/订阅仅入库)
|
||||
- NUXT_SMTP_HOST=${SMTP_HOST:-}
|
||||
- NUXT_SMTP_PORT=${SMTP_PORT:-465}
|
||||
- NUXT_SMTP_USER=${SMTP_USER:-}
|
||||
- NUXT_SMTP_PASS=${SMTP_PASS:-}
|
||||
- NUXT_SMTP_FROM=${SMTP_FROM:-}
|
||||
- NUXT_SMTP_CONTACT_TO=${SMTP_CONTACT_TO:-}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
|
||||
+18
-4
@@ -297,7 +297,11 @@
|
||||
"newsletterNote": "No noise. Just curated updates.",
|
||||
"copyright": "© 2026 ArcticNewOne Studio",
|
||||
"address": "Binhe West Road, Qixingguan District, Bijie City, Guizhou Province",
|
||||
"wechat": "WeChat"
|
||||
"wechat": "WeChat",
|
||||
"newsletterSuccess": "Subscribed! Thank you for your support.",
|
||||
"newsletterError": "Subscription failed. Please try again later.",
|
||||
"newsletterAlreadySubscribed": "This email is already subscribed.",
|
||||
"newsletterInvalidEmail": "Please enter a valid email address"
|
||||
},
|
||||
"work": {
|
||||
"title": "Our Work",
|
||||
@@ -404,7 +408,11 @@
|
||||
"sent": "Sent!",
|
||||
"retry": "Try Again",
|
||||
"successMessage": "Message sent successfully! We will get back to you soon.",
|
||||
"errorMessage": "Failed to send message. Please try again or contact us directly."
|
||||
"errorMessage": "Failed to send message. Please try again or contact us directly.",
|
||||
"invalidName": "Please enter your name",
|
||||
"invalidEmail": "Invalid email format",
|
||||
"invalidSubject": "Subject is too long (max 255 characters)",
|
||||
"invalidMessage": "Message must be at least 10 characters"
|
||||
},
|
||||
"info": {
|
||||
"email": "chenchun{'@'}virtheart.com",
|
||||
@@ -503,7 +511,6 @@
|
||||
"loginButton": "Login",
|
||||
"loggingIn": "Logging in...",
|
||||
"loginError": "Login failed. Please check your credentials.",
|
||||
"demoHint": "Demo: Use any account and password to login",
|
||||
"noAccount": "Don't have an account?",
|
||||
"createAccount": "Sign Up",
|
||||
"register": "Sign Up",
|
||||
@@ -523,6 +530,13 @@
|
||||
"passwordMismatch": "Passwords do not match",
|
||||
"invalidPhone": "Invalid phone number format",
|
||||
"alreadyHaveAccount": "Already have an account?",
|
||||
"backToLogin": "Back to Login"
|
||||
"backToLogin": "Back to Login",
|
||||
"invalidUsername": "Username must be 2-50 characters (letters, numbers, underscore)",
|
||||
"invalidEmail": "Invalid email format",
|
||||
"passwordTooShort": "Password must be at least 6 characters",
|
||||
"usernameTaken": "This username is already taken",
|
||||
"emailTaken": "This email is already registered",
|
||||
"phoneTaken": "This phone number is already registered",
|
||||
"invalidCredentials": "Incorrect account or password"
|
||||
}
|
||||
}
|
||||
|
||||
+18
-4
@@ -297,7 +297,11 @@
|
||||
"newsletterNote": "无广告干扰。仅提供精选更新。",
|
||||
"copyright": "© 2026 北极新一工作室",
|
||||
"address": "贵州省毕节市七星关区滨河西路",
|
||||
"wechat": "微信"
|
||||
"wechat": "微信",
|
||||
"newsletterSuccess": "订阅成功!感谢您的关注。",
|
||||
"newsletterError": "订阅失败,请稍后重试。",
|
||||
"newsletterAlreadySubscribed": "该邮箱已订阅过啦。",
|
||||
"newsletterInvalidEmail": "请输入有效的邮箱地址"
|
||||
},
|
||||
"work": {
|
||||
"title": "我们的作品",
|
||||
@@ -404,7 +408,11 @@
|
||||
"sent": "已发送!",
|
||||
"retry": "重试",
|
||||
"successMessage": "消息发送成功!我们会尽快回复您。",
|
||||
"errorMessage": "发送失败,请重试或直接联系我们。"
|
||||
"errorMessage": "发送失败,请重试或直接联系我们。",
|
||||
"invalidName": "请填写您的姓名",
|
||||
"invalidEmail": "邮箱格式不正确",
|
||||
"invalidSubject": "主题过长(最多 255 个字符)",
|
||||
"invalidMessage": "留言内容至少 10 个字符"
|
||||
},
|
||||
"info": {
|
||||
"email": "chenchun{'@'}virtheart.com",
|
||||
@@ -503,7 +511,6 @@
|
||||
"loginButton": "登录",
|
||||
"loggingIn": "登录中...",
|
||||
"loginError": "登录失败,请检查您的凭据。",
|
||||
"demoHint": "演示:使用任意账号和密码即可登录",
|
||||
"noAccount": "还没有账号?",
|
||||
"createAccount": "立即注册",
|
||||
"register": "注册账号",
|
||||
@@ -523,6 +530,13 @@
|
||||
"passwordMismatch": "两次输入的密码不一致",
|
||||
"invalidPhone": "手机号格式不正确",
|
||||
"alreadyHaveAccount": "已有账号?",
|
||||
"backToLogin": "返回登录"
|
||||
"backToLogin": "返回登录",
|
||||
"invalidUsername": "用户名格式不正确(2-50 位,中英文、数字、下划线)",
|
||||
"invalidEmail": "邮箱格式不正确",
|
||||
"passwordTooShort": "密码长度至少 6 位",
|
||||
"usernameTaken": "该用户名已被注册",
|
||||
"emailTaken": "该邮箱已被注册",
|
||||
"phoneTaken": "该手机号已被注册",
|
||||
"invalidCredentials": "账号或密码错误"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,4 +44,17 @@ export default defineNuxtConfig({
|
||||
strategy: 'no_prefix',
|
||||
detectBrowserLanguage: false,
|
||||
},
|
||||
runtimeConfig: {
|
||||
// 服务端私有配置(仅服务端可读,通过 NUXT_* 环境变量覆盖,绝不暴露给客户端)
|
||||
databaseUrl: '', // NUXT_DATABASE_URL 例: postgres://user:pass@host:5432/db
|
||||
jwtSecret: 'dev-only-secret-change-in-production', // NUXT_JWT_SECRET
|
||||
smtp: {
|
||||
host: '', // NUXT_SMTP_HOST
|
||||
port: 465, // NUXT_SMTP_PORT
|
||||
user: '', // NUXT_SMTP_USER
|
||||
pass: '', // NUXT_SMTP_PASS
|
||||
from: '', // NUXT_SMTP_FROM
|
||||
contactTo: '', // NUXT_SMTP_CONTACT_TO(联系表单/订阅通知收件人)
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
+7
-1
@@ -15,15 +15,21 @@
|
||||
"@nuxt/icon": "2.2.1",
|
||||
"@nuxtjs/i18n": "10.3.0",
|
||||
"@pinia/nuxt": "0.11.3",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"gsap": "^3.15.0",
|
||||
"jose": "^6.2.8",
|
||||
"lenis": "^1.3.23",
|
||||
"nodemailer": "^9.0.4",
|
||||
"nuxt": "^4.4.2",
|
||||
"pg": "^8.22.0",
|
||||
"pinia": "^3.0.4",
|
||||
"vue": "^3.5.32",
|
||||
"vue-router": "^5.0.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@iconify-json/ph": "1.2.2",
|
||||
"@nuxtjs/tailwindcss": "6.14.0"
|
||||
"@nuxtjs/tailwindcss": "6.14.0",
|
||||
"@types/nodemailer": "^8.0.1",
|
||||
"@types/pg": "^8.20.4"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+430
-209
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,40 @@
|
||||
import { compare } from 'bcryptjs'
|
||||
import { useDb } from '../../db'
|
||||
import { apiError, toPublicUser } from '../../utils/api'
|
||||
import { setAuthCookie, signToken } from '../../utils/auth'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event)
|
||||
const account = String(body?.account || '').trim().toLowerCase()
|
||||
const password = String(body?.password || '')
|
||||
|
||||
if (!account || !password) {
|
||||
throw apiError(event, 'auth.invalidCredentials')
|
||||
}
|
||||
|
||||
const pool = useDb()
|
||||
|
||||
// account 支持:用户名 / 邮箱 / 手机号(用户名与邮箱统一小写匹配)
|
||||
const result = await pool.query(
|
||||
`SELECT id, username, email, phone, password_hash, avatar_url
|
||||
FROM users
|
||||
WHERE LOWER(username) = $1 OR email = $1 OR phone = $1`,
|
||||
[account]
|
||||
)
|
||||
const user = result.rows[0]
|
||||
|
||||
if (!user) throw apiError(event, 'auth.invalidCredentials', 401)
|
||||
|
||||
const passwordOk = await compare(password, user.password_hash)
|
||||
if (!passwordOk) throw apiError(event, 'auth.invalidCredentials', 401)
|
||||
|
||||
const token = await signToken({
|
||||
id: Number(user.id),
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
avatarUrl: user.avatar_url,
|
||||
})
|
||||
setAuthCookie(event, token)
|
||||
|
||||
return { success: true, user: toPublicUser(user) }
|
||||
})
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clearAuthCookie } from '../../utils/auth'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
clearAuthCookie(event)
|
||||
return { success: true }
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useDb } from '../../db'
|
||||
import { toPublicUser } from '../../utils/api'
|
||||
import { clearAuthCookie, getAuthUser } from '../../utils/auth'
|
||||
|
||||
/**
|
||||
* 通过 Cookie 恢复当前登录用户(未登录或 token 失效返回 { user: null })
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = await getAuthUser(event)
|
||||
if (!auth) {
|
||||
return { user: null }
|
||||
}
|
||||
|
||||
// 从数据库读取最新用户信息(例如头像更新后保持同步)
|
||||
const result = await useDb().query(
|
||||
'SELECT id, username, email, phone, avatar_url, created_at FROM users WHERE id = $1',
|
||||
[auth.id]
|
||||
)
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
clearAuthCookie(event)
|
||||
return { user: null }
|
||||
}
|
||||
|
||||
return { user: toPublicUser(result.rows[0]) }
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import { hash } from 'bcryptjs'
|
||||
import { useDb } from '../../db'
|
||||
import { apiError, isValidEmail, isValidPhone, isValidUsername, toPublicUser } from '../../utils/api'
|
||||
import { setAuthCookie, signToken } from '../../utils/auth'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event)
|
||||
const username = String(body?.username || '').trim()
|
||||
const email = String(body?.email || '').trim().toLowerCase()
|
||||
const phone = String(body?.phone || '').trim()
|
||||
const password = String(body?.password || '')
|
||||
|
||||
// 参数校验
|
||||
if (!isValidUsername(username)) throw apiError(event, 'auth.invalidUsername')
|
||||
if (!isValidEmail(email)) throw apiError(event, 'auth.invalidEmail')
|
||||
if (phone && !isValidPhone(phone)) throw apiError(event, 'auth.invalidPhone')
|
||||
if (password.length < 6 || password.length > 72) throw apiError(event, 'auth.passwordTooShort')
|
||||
|
||||
const pool = useDb()
|
||||
|
||||
// 唯一性检查(用户名 / 邮箱 / 手机号)
|
||||
const dup = await pool.query(
|
||||
'SELECT username, email, phone FROM users WHERE username = $1 OR email = $2 OR ($3 <> \'\' AND phone = $3)',
|
||||
[username, email, phone]
|
||||
)
|
||||
if (dup.rows.length > 0) {
|
||||
const row = dup.rows[0]
|
||||
if (row.username === username) throw apiError(event, 'auth.usernameTaken', 409)
|
||||
if (row.email === email) throw apiError(event, 'auth.emailTaken', 409)
|
||||
throw apiError(event, 'auth.phoneTaken', 409)
|
||||
}
|
||||
|
||||
// 创建用户
|
||||
const passwordHash = await hash(password, 10)
|
||||
const result = await pool.query(
|
||||
`INSERT INTO users (username, email, phone, password_hash)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, username, email, phone, avatar_url, created_at`,
|
||||
[username, email, phone || null, passwordHash]
|
||||
)
|
||||
const user = result.rows[0]
|
||||
|
||||
// 注册成功即自动登录(httpOnly Cookie)
|
||||
const token = await signToken({
|
||||
id: Number(user.id),
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
avatarUrl: user.avatar_url,
|
||||
})
|
||||
setAuthCookie(event, token)
|
||||
|
||||
return { success: true, user: toPublicUser(user) }
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useDb } from '../db'
|
||||
import { apiError, isValidEmail } from '../utils/api'
|
||||
import { sendMail } from '../utils/mail'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event)
|
||||
const name = String(body?.name || '').trim()
|
||||
const email = String(body?.email || '').trim().toLowerCase()
|
||||
const subject = String(body?.subject || '').trim()
|
||||
const message = String(body?.message || '').trim()
|
||||
|
||||
// 参数校验
|
||||
if (!name || name.length > 100) throw apiError(event, 'contact.invalidName')
|
||||
if (!isValidEmail(email)) throw apiError(event, 'contact.invalidEmail')
|
||||
if (subject.length > 255) throw apiError(event, 'contact.invalidSubject')
|
||||
if (message.length < 10 || message.length > 5000) throw apiError(event, 'contact.invalidMessage')
|
||||
|
||||
// 入库(无论邮件是否配置成功,留言都不丢失)
|
||||
const ip = getRequestIP(event, { xForwardedFor: true }) || null
|
||||
await useDb().query(
|
||||
`INSERT INTO contact_messages (name, email, subject, message, ip)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
[name, email, subject, message, ip]
|
||||
)
|
||||
|
||||
// 邮件通知(SMTP 未配置时静默跳过,见 sendMail)
|
||||
const mailText = [
|
||||
`姓名: ${name}`,
|
||||
`邮箱: ${email}`,
|
||||
`主题: ${subject || '(无主题)'}`,
|
||||
``,
|
||||
`留言内容:`,
|
||||
message,
|
||||
``,
|
||||
`IP: ${ip || '未知'}`,
|
||||
`时间: ${new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`,
|
||||
].join('\n')
|
||||
await sendMail({
|
||||
subject: `[网站联系] ${subject || '来自网站的留言'}`,
|
||||
text: mailText,
|
||||
})
|
||||
|
||||
return { success: true }
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useDb } from '../../db'
|
||||
import { apiError, isValidEmail } from '../../utils/api'
|
||||
import { sendMail } from '../../utils/mail'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event)
|
||||
const email = String(body?.email || '').trim().toLowerCase()
|
||||
|
||||
if (!isValidEmail(email)) {
|
||||
throw apiError(event, 'newsletter.invalidEmail')
|
||||
}
|
||||
|
||||
const pool = useDb()
|
||||
|
||||
try {
|
||||
await pool.query('INSERT INTO newsletter_subscribers (email) VALUES ($1)', [email])
|
||||
} catch (err: any) {
|
||||
// 唯一约束冲突 = 已订阅
|
||||
if (err?.code === '23505') {
|
||||
throw apiError(event, 'newsletter.alreadySubscribed', 409)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
// 邮件通知(SMTP 未配置时静默跳过,见 sendMail)
|
||||
await sendMail({
|
||||
subject: '[网站订阅] 新订阅者',
|
||||
text: `邮箱 ${email} 于 ${new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })} 订阅了网站资讯。`,
|
||||
})
|
||||
|
||||
return { success: true }
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Pool } from 'pg'
|
||||
import { useRuntimeConfig } from '#imports'
|
||||
|
||||
let _pool: Pool | null = null
|
||||
|
||||
/**
|
||||
* 获取 PostgreSQL 连接池(懒加载单例)
|
||||
*/
|
||||
export function useDb(): Pool {
|
||||
if (_pool) {
|
||||
return _pool
|
||||
}
|
||||
|
||||
const config = useRuntimeConfig()
|
||||
const connectionString = config.databaseUrl as string
|
||||
|
||||
if (!connectionString) {
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: 'DATABASE_URL 未配置,请设置 NUXT_DATABASE_URL 环境变量',
|
||||
})
|
||||
}
|
||||
|
||||
_pool = new Pool({ connectionString, max: 10 })
|
||||
|
||||
// 连接失败时输出可读错误,避免静默挂起
|
||||
_pool.on('error', (err) => {
|
||||
console.error('[db] PostgreSQL 连接池错误:', err.message)
|
||||
})
|
||||
|
||||
return _pool
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* 数据库 Schema(幂等:CREATE TABLE IF NOT EXISTS,可在应用启动时安全重复执行)
|
||||
*/
|
||||
export const SCHEMA_SQL = `
|
||||
-- 用户表(注册/登录)
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username VARCHAR(50) NOT NULL UNIQUE,
|
||||
email VARCHAR(255) NOT NULL UNIQUE,
|
||||
phone VARCHAR(20) UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
avatar_url TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- 联系表单留言
|
||||
CREATE TABLE IF NOT EXISTS contact_messages (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
email VARCHAR(255) NOT NULL,
|
||||
subject VARCHAR(255) NOT NULL DEFAULT '',
|
||||
message TEXT NOT NULL,
|
||||
ip VARCHAR(45),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- 资讯订阅者
|
||||
CREATE TABLE IF NOT EXISTS newsletter_subscribers (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
email VARCHAR(255) NOT NULL UNIQUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- 常用索引
|
||||
CREATE INDEX IF NOT EXISTS idx_contact_messages_created_at ON contact_messages (created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_newsletter_subscribers_created_at ON newsletter_subscribers (created_at DESC);
|
||||
`
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useDb } from '../db'
|
||||
import { SCHEMA_SQL } from '../db/schema'
|
||||
|
||||
/**
|
||||
* 应用启动时自动建表(幂等),保证表结构就绪
|
||||
*/
|
||||
export default defineNitroPlugin(async () => {
|
||||
try {
|
||||
const pool = useDb()
|
||||
await pool.query('SELECT 1')
|
||||
await pool.query(SCHEMA_SQL)
|
||||
console.log('[db] PostgreSQL 连接成功,schema 已就绪')
|
||||
} catch (err: any) {
|
||||
// 数据库不可用时不允许静默:打印错误,但让服务继续启动(API 调用时会返回明确的 500)
|
||||
console.error('[db] PostgreSQL 初始化失败:', err?.message || err)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* 统一 API 错误:抛出的 statusMessage 即前端 i18n 错误码(如 'auth.emailTaken')
|
||||
*/
|
||||
export function apiError(event: any, code: string, statusCode = 400): never {
|
||||
throw createError({
|
||||
statusCode,
|
||||
statusMessage: code,
|
||||
fatal: false,
|
||||
})
|
||||
}
|
||||
|
||||
/** 数据库用户行 -> 对外公开的用户对象 */
|
||||
export function toPublicUser(row: any) {
|
||||
return {
|
||||
id: Number(row.id),
|
||||
username: row.username,
|
||||
email: row.email,
|
||||
phone: row.phone ?? undefined,
|
||||
avatarUrl: row.avatar_url ?? undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** 通用邮箱格式校验 */
|
||||
export function isValidEmail(email: string): boolean {
|
||||
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
|
||||
}
|
||||
|
||||
/** 通用手机号校验(中国大陆 11 位) */
|
||||
export function isValidPhone(phone: string): boolean {
|
||||
return /^1[3-9]\d{9}$/.test(phone)
|
||||
}
|
||||
|
||||
/** 用户名校验:2-50 位,中英文、数字、下划线 */
|
||||
export function isValidUsername(username: string): boolean {
|
||||
return /^[a-zA-Z0-9_\u4e00-\u9fa5]{2,50}$/.test(username)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { SignJWT, jwtVerify } from 'jose'
|
||||
import { useRuntimeConfig } from '#imports'
|
||||
|
||||
export const AUTH_COOKIE_NAME = 'arcticnewone_token'
|
||||
export const JWT_MAX_AGE_SECONDS = 60 * 60 * 24 * 7 // 7 天
|
||||
|
||||
export interface AuthUserPayload {
|
||||
id: number
|
||||
username: string
|
||||
email: string
|
||||
avatarUrl?: string | null
|
||||
}
|
||||
|
||||
function getSecretKey(): Uint8Array {
|
||||
const config = useRuntimeConfig()
|
||||
const secret = (config.jwtSecret as string) || 'dev-only-secret-change-in-production'
|
||||
return new TextEncoder().encode(secret)
|
||||
}
|
||||
|
||||
/** 签发 JWT */
|
||||
export async function signToken(user: AuthUserPayload): Promise<string> {
|
||||
return await new SignJWT({
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
avatarUrl: user.avatarUrl ?? null,
|
||||
})
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setSubject(String(user.id))
|
||||
.setIssuedAt()
|
||||
.setExpirationTime(`${JWT_MAX_AGE_SECONDS}s`)
|
||||
.sign(getSecretKey())
|
||||
}
|
||||
|
||||
/** 校验 JWT,失败返回 null */
|
||||
export async function verifyToken(token: string): Promise<AuthUserPayload | null> {
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, getSecretKey())
|
||||
if (!payload.sub) return null
|
||||
return {
|
||||
id: Number(payload.sub),
|
||||
username: String(payload.username || ''),
|
||||
email: String(payload.email || ''),
|
||||
avatarUrl: payload.avatarUrl ? String(payload.avatarUrl) : null,
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** 从请求 Cookie 解析当前登录用户(未登录返回 null) */
|
||||
export async function getAuthUser(event: any): Promise<AuthUserPayload | null> {
|
||||
const token = getCookie(event, AUTH_COOKIE_NAME)
|
||||
if (!token) return null
|
||||
return await verifyToken(token)
|
||||
}
|
||||
|
||||
/** 写入登录 Cookie(httpOnly,生产环境自动启用 Secure) */
|
||||
export function setAuthCookie(event: any, token: string): void {
|
||||
const isProd = process.env.NODE_ENV === 'production'
|
||||
setCookie(event, AUTH_COOKIE_NAME, token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: isProd,
|
||||
path: '/',
|
||||
maxAge: JWT_MAX_AGE_SECONDS,
|
||||
})
|
||||
}
|
||||
|
||||
/** 清除登录 Cookie */
|
||||
export function clearAuthCookie(event: any): void {
|
||||
deleteCookie(event, AUTH_COOKIE_NAME, { path: '/' })
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import nodemailer from 'nodemailer'
|
||||
import { useRuntimeConfig } from '#imports'
|
||||
|
||||
interface MailOptions {
|
||||
to?: string
|
||||
subject: string
|
||||
text: string
|
||||
html?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送邮件。SMTP 未配置时仅记录日志(数据已入库,不阻塞业务)。
|
||||
* 环境变量: NUXT_SMTP_HOST / NUXT_SMTP_PORT / NUXT_SMTP_USER / NUXT_SMTP_PASS
|
||||
* NUXT_SMTP_FROM / NUXT_SMTP_CONTACT_TO
|
||||
*/
|
||||
export async function sendMail({ to, subject, text, html }: MailOptions): Promise<void> {
|
||||
const config = useRuntimeConfig()
|
||||
const smtp = config.smtp as { host?: string; port?: number; user?: string; pass?: string; from?: string; contactTo?: string }
|
||||
|
||||
if (!smtp?.host || !smtp?.user || !smtp?.pass) {
|
||||
console.log(`[mail] SMTP 未配置,跳过发送。主题: ${subject},收件人: ${to || smtp?.contactTo || '(未配置)'}`)
|
||||
return
|
||||
}
|
||||
|
||||
const port = Number(smtp.port) || 465
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: smtp.host,
|
||||
port,
|
||||
secure: port === 465,
|
||||
auth: { user: smtp.user, pass: smtp.pass },
|
||||
})
|
||||
|
||||
await transporter.sendMail({
|
||||
from: smtp.from || smtp.user,
|
||||
to: to || smtp.contactTo || smtp.user,
|
||||
subject,
|
||||
text,
|
||||
html,
|
||||
})
|
||||
console.log(`[mail] 邮件已发送: ${subject} -> ${to || smtp.contactTo}`)
|
||||
}
|
||||
Reference in New Issue
Block a user