import { readBody, createError } from 'h3' import { getDb } from '../../utils/db' import { requireUser, verifyPassword, hashPassword } from '../../utils/auth' import { isValidPassword } from '../../utils/validation' /** * 修改密码:校验当前密码 -> 新密码强度 -> 更新 */ export default defineEventHandler(async (event) => { const user = requireUser(event) const body = await readBody(event) const currentPassword = String(body?.currentPassword ?? '') const newPassword = String(body?.newPassword ?? '') const row = getDb().prepare('SELECT password_hash FROM users WHERE id = ?').get(user.id) as | { password_hash: string } | undefined if (!row || !(await verifyPassword(currentPassword, row.password_hash))) { throw createError({ statusCode: 400, message: '当前密码不正确', data: { code: 'WRONG_PASSWORD' } }) } if (!isValidPassword(newPassword)) { throw createError({ statusCode: 400, message: '新密码至少需要 8 位', data: { code: 'VALIDATION_ERROR' } }) } const passwordHash = await hashPassword(newPassword) getDb().prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(passwordHash, user.id) return { ok: true } })