28 lines
990 B
TypeScript
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 }
|
|
})
|