Files
dticket.tootaio.com/server/api/auth/change-password.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.5 KiB
TypeScript

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 { updateUserPassword } from '../../utils/user-repository'
import { requireExistingUser } from '../../utils/users'
export default defineEventHandler(async (event) => {
const auth = await requireAuth(event)
const body = await readBody<{
currentPassword?: string
newPassword?: string
}>(event)
const currentPassword = body.currentPassword?.trim() || ''
const newPassword = body.newPassword?.trim() || ''
assertBadRequest(currentPassword, 'Current password and new password are required')
assertBadRequest(newPassword, 'Current password and new password are required')
if (newPassword.length < MIN_PASSWORD_LENGTH) {
httpError(400, `New password must be at least ${MIN_PASSWORD_LENGTH} characters`)
}
if (currentPassword === newPassword) {
httpError(400, 'New password must be different from the current password')
}
const currentPasswordMatches = await verifyPassword(currentPassword, auth.user.passwordHash)
if (!currentPasswordMatches) {
httpError(400, 'Current password is incorrect')
}
const passwordHash = await hashPassword(newPassword)
await updateUserPassword({
userId: auth.user.id,
passwordHash,
mustChangePassword: false
})
const updatedUser = await requireExistingUser(auth.user.id, 'Unable to load updated user')
return {
user: updatedUser
}
})