Files
money.sori.studio/server/api/auth/register.post.ts

38 lines
1.2 KiB
TypeScript

import { hash } from 'bcryptjs'
import { readBody, createError } from 'h3'
import { prisma } from '../../utils/db'
import { setSession } from '../../utils/auth'
import { createDefaultMoneyData } from '../../utils/defaults'
export default defineEventHandler(async (event) => {
const body = await readBody<{ email: string; password: string; name?: string }>(event)
const email = body.email?.trim().toLowerCase()
const password = body.password || ''
const name = body.name?.trim() || email?.split('@')[0] || '사용자'
if (!email || !email.includes('@') || password.length < 8) {
throw createError({ statusCode: 400, statusMessage: 'Invalid registration' })
}
const exists = await prisma.user.findUnique({ where: { email } })
if (exists) {
throw createError({ statusCode: 409, statusMessage: 'Email already exists' })
}
const user = await prisma.$transaction(async (tx) => {
const created = await tx.user.create({
data: {
email,
name,
passwordHash: await hash(password, 10)
}
})
await createDefaultMoneyData(tx, created.id)
return created
})
setSession(event, user.id)
return { id: user.id, email: user.email, name: user.name }
})