Files
money.sori.studio/server/api/auth/password.post.ts
2026-08-13 18:20:36 +09:00

28 lines
990 B
TypeScript

import { compare, hash } from 'bcryptjs'
import { readBody, createError } from 'h3'
import { prisma } from '../../utils/db'
import { requireUser } from '../../utils/auth'
export default defineEventHandler(async (event) => {
const sessionUser = await requireUser(event)
const body = await readBody<{ currentPassword?: string; nextPassword?: string }>(event)
const currentPassword = body.currentPassword || ''
const nextPassword = body.nextPassword || ''
if (nextPassword.length < 8) {
throw createError({ statusCode: 400, statusMessage: 'Password must be at least 8 characters' })
}
const user = await prisma.user.findUnique({ where: { id: sessionUser.id } })
if (!user || !(await compare(currentPassword, user.passwordHash))) {
throw createError({ statusCode: 401, statusMessage: 'Current password is invalid' })
}
await prisma.user.update({
where: { id: user.id },
data: { passwordHash: await hash(nextPassword, 10) }
})
return { ok: true }
})