Files
dticket.tootaio.com/server/api/admin/users.post.ts
xiaomai 07e5d42005 refactor: centralize validation, error handling, and formatting logic
Extract shared auth logic and validation rules to shared/auth.ts
Introduce utility functions for HTTP errors and user input parsing
Standardize error messages and date formatting across the app
2026-04-12 20:29:39 +08:00

50 lines
1.1 KiB
TypeScript

import { DEFAULT_USER_PASSWORD, type UserRole } from '~~/shared/auth'
import { requireRole } from '../../utils/auth'
import { mapDatabaseError } from '../../utils/http'
import { hashPassword } from '../../utils/password'
import { createUser } from '../../utils/user-repository'
import { parseCreateUserInput } from '../../utils/users'
export default defineEventHandler(async (event) => {
const auth = await requireRole(event, 'super_admin')
const body = await readBody<{
username?: string
fullName?: string
phoneNumber?: string
role?: UserRole
}>(event)
const {
username,
fullName,
phoneNumber,
role
} = parseCreateUserInput(body)
const passwordHash = await hashPassword(DEFAULT_USER_PASSWORD)
try {
const user = await createUser({
username,
fullName,
phoneNumber,
role,
passwordHash,
createdBy: auth.user.id
})
return {
user,
defaultPassword: DEFAULT_USER_PASSWORD
}
} catch (error) {
mapDatabaseError(error, {
'23505': {
statusCode: 409,
statusMessage: 'Username already exists'
}
})
}
})