import { readBody, createError } from 'h3' import { getDb } from '../../utils/db' import { hashPassword, createSession, setSessionCookie, toPublicUser, type UserRow } from '../../utils/auth' import { isValidUsername, isValidEmail, isValidPassword, isValidPhone } from '../../utils/validation' /** * 注册:校验 -> scrypt 哈希 -> 落库 -> 建立会话 */ 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 createError({ statusCode: 400, message: '用户名需为 2-20 位字符', data: { code: 'VALIDATION_ERROR' } }) } if (!isValidEmail(email)) { throw createError({ statusCode: 400, message: '邮箱格式不正确', data: { code: 'VALIDATION_ERROR' } }) } if (!isValidPassword(password)) { throw createError({ statusCode: 400, message: '密码至少需要 8 位', data: { code: 'VALIDATION_ERROR' } }) } if (phone && !isValidPhone(phone)) { throw createError({ statusCode: 400, message: '手机号格式不正确', data: { code: 'VALIDATION_ERROR' } }) } const db = getDb() const existing = db .prepare('SELECT username, email FROM users WHERE username = ? OR email = ?') .get(username, email) as { username: string; email: string } | undefined if (existing) { if (existing.username === username) { throw createError({ statusCode: 400, message: '用户名已被使用', data: { code: 'USERNAME_TAKEN' } }) } throw createError({ statusCode: 400, message: '该邮箱已被注册', data: { code: 'EMAIL_TAKEN' } }) } const passwordHash = await hashPassword(password) const info = db .prepare('INSERT INTO users (username, email, phone, password_hash) VALUES (?, ?, ?, ?)') .run(username, email, phone || null, passwordHash) const user = db .prepare('SELECT id, username, email, phone, role, created_at FROM users WHERE id = ?') .get(info.lastInsertRowid) as UserRow const token = createSession(user.id) setSessionCookie(event, token) return { user: toPublicUser(user) } })