import { readBody, createError } from 'h3' import { getDb } from '../../utils/db' import { verifyPassword, createSession, setSessionCookie, toPublicUser, type UserRow } from '../../utils/auth' /** * 登录:账号(用户名或邮箱)+ 密码 -> 校验 -> 建立会话 */ export default defineEventHandler(async (event) => { const body = await readBody(event) const account = String(body?.account ?? '').trim() const password = String(body?.password ?? '') if (!account || !password) { throw createError({ statusCode: 400, message: '请输入账号与密码', data: { code: 'VALIDATION_ERROR' } }) } const db = getDb() const user = db .prepare('SELECT * FROM users WHERE username = ? OR email = ?') .get(account, account.toLowerCase()) as (UserRow & { password_hash: string }) | undefined if (!user || !(await verifyPassword(password, user.password_hash))) { throw createError({ statusCode: 401, message: '账号或密码错误', data: { code: 'INVALID_CREDENTIALS' } }) } const token = createSession(user.id) setSessionCookie(event, token) return { user: toPublicUser(user) } })