53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { createUser, generateToken } from '@/lib/auth'
|
|
import { prisma } from '@/lib/db'
|
|
import { userRegistrationSchema } from '@/lib/validation'
|
|
import { z } from 'zod'
|
|
|
|
export const runtime = 'nodejs'
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
const body = await request.json()
|
|
|
|
// Validate input
|
|
const result = userRegistrationSchema.safeParse(body)
|
|
if (!result.success) {
|
|
const errors = result.error.errors.map(err => err.message).join(', ')
|
|
return NextResponse.json({ error: errors }, { status: 400 })
|
|
}
|
|
|
|
const { email, password, name } = result.data
|
|
|
|
// Check if user exists
|
|
const existing = await prisma.user.findUnique({ where: { email } })
|
|
if (existing) {
|
|
return NextResponse.json({ error: 'Utilizatorul există deja' }, { status: 409 })
|
|
}
|
|
|
|
// Create user
|
|
const user = await createUser(email, password, name)
|
|
const token = generateToken(user.id)
|
|
|
|
// Create session
|
|
await prisma.session.create({
|
|
data: {
|
|
userId: user.id,
|
|
token,
|
|
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
|
}
|
|
})
|
|
|
|
return NextResponse.json({
|
|
user: { id: user.id, email: user.email, name: user.name },
|
|
token
|
|
})
|
|
} catch (error) {
|
|
console.error('Registration error:', error)
|
|
if (error instanceof z.ZodError) {
|
|
return NextResponse.json({ error: 'Date de intrare invalide' }, { status: 400 })
|
|
}
|
|
return NextResponse.json({ error: 'Eroare de server' }, { status: 500 })
|
|
}
|
|
}
|