Add account registration flow
This commit is contained in:
34
server/api/auth/register.post.ts
Normal file
34
server/api/auth/register.post.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
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.user.create({
|
||||
data: {
|
||||
email,
|
||||
name,
|
||||
passwordHash: await hash(password, 10)
|
||||
}
|
||||
})
|
||||
|
||||
await createDefaultMoneyData(prisma, user.id)
|
||||
setSession(event, user.id)
|
||||
|
||||
return { id: user.id, email: user.email, name: user.name }
|
||||
})
|
||||
36
server/utils/defaults.ts
Normal file
36
server/utils/defaults.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import type { PrismaClient } from '@prisma/client'
|
||||
|
||||
export async function createDefaultMoneyData(prisma: PrismaClient, userId: string) {
|
||||
const cash = await prisma.asset.create({
|
||||
data: {
|
||||
userId,
|
||||
name: '기본자산',
|
||||
balanceType: 'cumulative',
|
||||
initialBalance: 0,
|
||||
sortOrder: 0
|
||||
}
|
||||
})
|
||||
|
||||
const incomeParent = await prisma.category.create({
|
||||
data: { userId, type: 'income', name: '근로', sortOrder: 0 }
|
||||
})
|
||||
await prisma.category.create({
|
||||
data: { userId, type: 'income', name: '월급', parentId: incomeParent.id, sortOrder: 0 }
|
||||
})
|
||||
|
||||
const foodParent = await prisma.category.create({
|
||||
data: { userId, type: 'expense', name: '식비', sortOrder: 0 }
|
||||
})
|
||||
await prisma.category.create({
|
||||
data: { userId, type: 'expense', name: '외식', parentId: foodParent.id, sortOrder: 0 }
|
||||
})
|
||||
|
||||
const livingParent = await prisma.category.create({
|
||||
data: { userId, type: 'expense', name: '생활', sortOrder: 1 }
|
||||
})
|
||||
await prisma.category.create({
|
||||
data: { userId, type: 'expense', name: '마트', parentId: livingParent.id, sortOrder: 0 }
|
||||
})
|
||||
|
||||
return { cash }
|
||||
}
|
||||
Reference in New Issue
Block a user