feat: 新增 Nitro Server API 与 PostgreSQL 后端,接入用户系统/联系表单/资讯订阅

- server/api: 注册/登录/登出/会话恢复(JWT + httpOnly Cookie, bcrypt 密码哈希)
- server/api: 联系表单与资讯订阅入库,支持 SMTP 邮件通知(可选)
- 应用启动自动建表(幂等),docker-compose 新增 PostgreSQL 16 服务
- 前端移除全部 mock:user store、登录注册弹窗、联系表单、页脚订阅接入真实接口
- i18n 补充服务端错误码中英文案,移除 demoHint
- deploy: Deployment 环境变量(Secret 引用)、可选集群内 PostgreSQL(postgres.yaml)
- 新增 .env.example 与 README/deploy 文档更新
This commit is contained in:
2026-08-06 06:49:14 +08:00
parent 6192ae0a38
commit 4bef241544
29 changed files with 1320 additions and 354 deletions
+40
View File
@@ -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) }
})
+6
View File
@@ -0,0 +1,6 @@
import { clearAuthCookie } from '../../utils/auth'
export default defineEventHandler(async (event) => {
clearAuthCookie(event)
return { success: true }
})
+26
View File
@@ -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]) }
})
+53
View File
@@ -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) }
})
+44
View File
@@ -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 }
})
+32
View File
@@ -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 }
})