74 lines
1.8 KiB
TypeScript
74 lines
1.8 KiB
TypeScript
import { prisma } from "@/lib/prisma";
|
|
import bcrypt from "bcryptjs";
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const { email, password, name } = await req.json();
|
|
|
|
if (!email || !password) {
|
|
return NextResponse.json(
|
|
{ error: "Email and password are required" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Validate email format
|
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
if (!emailRegex.test(email)) {
|
|
return NextResponse.json(
|
|
{ error: "Invalid email format" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Validate password strength
|
|
if (password.length < 8) {
|
|
return NextResponse.json(
|
|
{ error: "Password must be at least 8 characters" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Check if user already exists
|
|
const existingUser = await prisma.user.findUnique({
|
|
where: { email: email.toLowerCase() },
|
|
});
|
|
|
|
if (existingUser) {
|
|
return NextResponse.json(
|
|
{ error: "An account with this email already exists" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Hash password
|
|
const passwordHash = await bcrypt.hash(password, 12);
|
|
|
|
// Create user with initial credits
|
|
const user = await prisma.user.create({
|
|
data: {
|
|
email: email.toLowerCase(),
|
|
passwordHash,
|
|
name: name || null,
|
|
credits: 50, // Starting credits
|
|
emailVerified: new Date(), // Auto-verify for now
|
|
},
|
|
select: {
|
|
id: true,
|
|
email: true,
|
|
name: true,
|
|
credits: true,
|
|
},
|
|
});
|
|
|
|
return NextResponse.json({ user }, { status: 201 });
|
|
} catch (error) {
|
|
console.error("Registration error:", error);
|
|
return NextResponse.json(
|
|
{ error: "Failed to create account" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|