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,5 +1,8 @@
import { normalizeUsername } from '~~/shared/auth'
import { signInUser } from '../../utils/auth'
import { assertBadRequest, httpError } from '../../utils/http'
import { verifyPassword } from '../../utils/password'
import { normalizeUsername, signInUser } from '../../utils/auth'
import { getUserByUsername } from '../../utils/user-repository'
export default defineEventHandler(async (event) => {
@@ -13,29 +16,19 @@ export default defineEventHandler(async (event) => {
const password = body.password?.trim() || ''
const remember = body.remember !== false
if (!username || !password) {
throw createError({
statusCode: 400,
statusMessage: 'Username and password are required'
})
}
assertBadRequest(username, 'Username and password are required')
assertBadRequest(password, 'Username and password are required')
const user = await getUserByUsername(username)
if (!user || !user.isActive) {
throw createError({
statusCode: 401,
statusMessage: 'Invalid username or password'
})
httpError(401, 'Invalid username or password')
}
const passwordMatches = await verifyPassword(password, user.passwordHash)
if (!passwordMatches) {
throw createError({
statusCode: 401,
statusMessage: 'Invalid username or password'
})
httpError(401, 'Invalid username or password')
}
const authenticatedUser = await signInUser(event, user, remember)