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
This commit is contained in:
2026-04-12 20:29:39 +08:00
parent 377a9617be
commit 07e5d42005
23 changed files with 294 additions and 267 deletions

View File

@@ -1,8 +1,10 @@
import { MIN_PASSWORD_LENGTH } from '~~/shared/auth'
import { assertBadRequest, httpError } from '../../utils/http'
import { requireAuth } from '../../utils/auth'
import { hashPassword, verifyPassword } from '../../utils/password'
import { getUserById, updateUserPassword } from '../../utils/user-repository'
import { updateUserPassword } from '../../utils/user-repository'
import { requireExistingUser } from '../../utils/users'
export default defineEventHandler(async (event) => {
const auth = await requireAuth(event)
@@ -14,34 +16,21 @@ export default defineEventHandler(async (event) => {
const currentPassword = body.currentPassword?.trim() || ''
const newPassword = body.newPassword?.trim() || ''
if (!currentPassword || !newPassword) {
throw createError({
statusCode: 400,
statusMessage: 'Current password and new password are required'
})
}
assertBadRequest(currentPassword, 'Current password and new password are required')
assertBadRequest(newPassword, 'Current password and new password are required')
if (newPassword.length < MIN_PASSWORD_LENGTH) {
throw createError({
statusCode: 400,
statusMessage: `New password must be at least ${MIN_PASSWORD_LENGTH} characters`
})
httpError(400, `New password must be at least ${MIN_PASSWORD_LENGTH} characters`)
}
if (currentPassword === newPassword) {
throw createError({
statusCode: 400,
statusMessage: 'New password must be different from the current password'
})
httpError(400, 'New password must be different from the current password')
}
const currentPasswordMatches = await verifyPassword(currentPassword, auth.user.passwordHash)
if (!currentPasswordMatches) {
throw createError({
statusCode: 400,
statusMessage: 'Current password is incorrect'
})
httpError(400, 'Current password is incorrect')
}
const passwordHash = await hashPassword(newPassword)
@@ -52,7 +41,7 @@ export default defineEventHandler(async (event) => {
mustChangePassword: false
})
const updatedUser = await getUserById(auth.user.id)
const updatedUser = await requireExistingUser(auth.user.id, 'Unable to load updated user')
return {
user: updatedUser