Files
dticket.tootaio.com/server/api/auth/login.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

40 lines
1.1 KiB
TypeScript

import { normalizeUsername } from '~~/shared/auth'
import { signInUser } from '../../utils/auth'
import { assertBadRequest, httpError } from '../../utils/http'
import { verifyPassword } from '../../utils/password'
import { getUserByUsername } from '../../utils/user-repository'
export default defineEventHandler(async (event) => {
const body = await readBody<{
username?: string
password?: string
remember?: boolean
}>(event)
const username = normalizeUsername(body.username || '')
const password = body.password?.trim() || ''
const remember = body.remember !== false
assertBadRequest(username, 'Username and password are required')
assertBadRequest(password, 'Username and password are required')
const user = await getUserByUsername(username)
if (!user || !user.isActive) {
httpError(401, 'Invalid username or password')
}
const passwordMatches = await verifyPassword(password, user.passwordHash)
if (!passwordMatches) {
httpError(401, 'Invalid username or password')
}
const authenticatedUser = await signInUser(event, user, remember)
return {
user: authenticatedUser
}
})