58 lines
1.5 KiB
TypeScript
58 lines
1.5 KiB
TypeScript
import { hashPassword } from '../../utils/password';
|
|
|
|
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',
|
|
});
|
|
}
|
|
|
|
const normalizedEmail = email.toLowerCase(); // Normalize email
|
|
|
|
// 2. Check if user already exists
|
|
const existingUser = await prisma.user.findUnique({
|
|
where: { email: normalizedEmail },
|
|
});
|
|
|
|
if (existingUser) {
|
|
throw createError({
|
|
statusCode: 409, // Conflict
|
|
statusMessage: 'Email already in use',
|
|
});
|
|
}
|
|
|
|
// 3. Hash password and create user
|
|
// WARNING: This hashPassword is a mock. Replace with a secure library like bcrypt before production.
|
|
const hashedPassword = await hashPassword(password);
|
|
const user = await prisma.user.create({
|
|
data: {
|
|
email: normalizedEmail,
|
|
password: hashedPassword,
|
|
nickname: nickname || 'New Smurf',
|
|
},
|
|
});
|
|
|
|
// NOTE: Registration does not automatically log in the user.
|
|
// The user needs to explicitly call the login endpoint after registration.
|
|
|
|
// 4. Return the new user, excluding sensitive fields and shortening DTO
|
|
return {
|
|
user: {
|
|
id: user.id,
|
|
email: user.email,
|
|
nickname: user.nickname,
|
|
}
|
|
};
|
|
});
|