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:
@@ -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) }
|
||||
})
|
||||
Reference in New Issue
Block a user