import { readBody, createError } from 'h3' import { requireAdmin } from '../../utils/auth' import { hashPassword } from '../../utils/adminAuth' import { getDb } from '../../utils/db' import { writeAudit } from '../../utils/audit' /** * 新增后台管理员(由当前管理员操作)。 */ export default defineEventHandler(async (event) => { requireAdmin(event) const body = await readBody(event) const username = String(body?.username || '').trim() const password = String(body?.password || '') if (!/^[a-zA-Z0-9_]{2,20}$/.test(username)) { throw createError({ statusCode: 400, message: '用户名需为 2-20 位字母、数字或下划线', data: { code: 'VALIDATION_ERROR' } }) } if (password.length < 8) { throw createError({ statusCode: 400, message: '密码至少需要 8 位', data: { code: 'VALIDATION_ERROR' } }) } const db = getDb() if (db.prepare('SELECT id FROM admin_users WHERE username = ?').get(username)) { throw createError({ statusCode: 400, message: '用户名已被使用', data: { code: 'USERNAME_TAKEN' } }) } const { lastInsertRowid } = db .prepare('INSERT INTO admin_users (username, password_hash) VALUES (?, ?)') .run(username, hashPassword(password)) writeAudit(event, 'create', `admin-user:${username}`) return { ok: true, admin: { id: Number(lastInsertRowid), username } } })