habits.andr33v.ru/server/api/auth/register.post.ts

51 lines
1.2 KiB
TypeScript

import { PrismaClient } from '@prisma/client';
import { hashPassword } from '../utils/password';
const prisma = new PrismaClient();
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const { email, password, nickname } = body;
// 1. Validate input
if (!email || !password) {
throw createError({
statusCode: 400,
statusMessage: 'Email and password are required',
});
}
if (password.length < 8) {
throw createError({
statusCode: 400,
statusMessage: 'Password must be at least 8 characters long',
});
}
// 2. Check if user already exists
const existingUser = await prisma.user.findUnique({
where: { email },
});
if (existingUser) {
throw createError({
statusCode: 409, // Conflict
statusMessage: 'Email already in use',
});
}
// 3. Hash password and create user
const hashedPassword = await hashPassword(password);
const user = await prisma.user.create({
data: {
email,
password: hashedPassword,
nickname: nickname || 'New Smurf',
},
});
// 4. Return the new user, excluding the password
const { password: _password, ...userWithoutPassword } = user;
return { user: userWithoutPassword };
});