import bcrypt from 'bcryptjs';import { createJWT } from '~/server/utils/jwt';import User from '~/server/models/User';export default defineEventHandler(async (event) => { const { email, password, name, role } = await readBody(event); const existingUser = await User.findOne({ email }); if (existingUser) { throw createError({ statusCode: 400, statusMessage: 'User already exists.', }); } const hashedPassword = await bcrypt.hash(password, 10); const user = new User({ email, password: hashedPassword, name, role: role || 'customer', }); await user.save(); const token = createJWT(user.email); await setAuth(event, token); return { success: true, user: { email: user.email, role: user.role } };});
async function onSubmit(data: any) { isLoading.value = true; try { const { data: response, error } = await useFetch('/api/auth/register', { method: 'POST', body: { name: data.name, email: data.email, password: data.password }, }); if (error.value) { userMessage.value = 'Registration failed. Please try again.'; toast.add({ title: userMessage.value, icon: 'i-heroicons-x-circle', color: 'red' }); } else { userMessage.value = 'Registration successful.'; toast.add({ title: userMessage.value, icon: 'i-heroicons-check-circle', color: 'green' }); isSuccess.value = true; router.push('/login'); } } catch (err) { console.error('Registration error:', err); userMessage.value = 'Something went wrong. Please try again.'; toast.add({ title: userMessage.value, icon: 'i-heroicons-x-circle', color: 'red' }); } finally { isLoading.value = false; } }