Implement Secure User Registration
Update the user registration service.
The registration process should:
- Normalize the email address.
- Check whether the email already exists.
- Hash the password.
- Create the user.
- Return the user without the password field.
The unique database index remains necessary because checking for an existing email before insertion does not prevent concurrent registration attempts.
Secure User Registration Service
import bcrypt from 'bcryptjs';
import { User } from '../models/user.model.js';
import { AppError } from '../utils/app-error.js';
export async function registerUser(userData) {
const email = userData.email.toLowerCase().trim();
const existingUser = await User.findOne({ email });
if (existingUser) {
throw new AppError('Email is already registered', 409);
}
const passwordHash = await bcrypt.hash(userData.password, 12);
const user = await User.create({
name: userData.name,
email,
password: passwordHash,
age: userData.age
});
return User.findById(user._id).select('-password');
}Normalizes email, checks for an existing account, hashes the password, creates the user, and returns a password-free document.
Key Takeaways
Normalize email addresses before storage.
Hash passwords before creating users.
Handle duplicate-key errors because pre-checks alone are insufficient.