50 lines
1.3 KiB
TypeScript
50 lines
1.3 KiB
TypeScript
|
|
'use server';
|
|
|
|
import db from '@/lib/db';
|
|
import type { User } from '@/types';
|
|
import { randomUUID } from 'crypto';
|
|
|
|
interface RegisterUserResult {
|
|
success: boolean;
|
|
message: string;
|
|
user?: User;
|
|
}
|
|
|
|
export async function registerUser(data: { name: string; email: string; password?: string }): Promise<RegisterUserResult> {
|
|
const { name, email } = data;
|
|
|
|
// Basic validation
|
|
if (!name || !email) {
|
|
return { success: false, message: 'Name and email are required.' };
|
|
}
|
|
|
|
try {
|
|
// Check if user already exists
|
|
const existingUser = db.prepare('SELECT * FROM users WHERE email = ?').get(email);
|
|
if (existingUser) {
|
|
return { success: false, message: 'An account with this email already exists.' };
|
|
}
|
|
|
|
const newUser: User = {
|
|
id: `user-${randomUUID()}`,
|
|
name,
|
|
email,
|
|
role: 'User',
|
|
avatarUrl: '',
|
|
bio: ''
|
|
};
|
|
|
|
const stmt = db.prepare(
|
|
'INSERT INTO users (id, name, email, role, avatarUrl, bio) VALUES (@id, @name, @email, @role, @avatarUrl, @bio)'
|
|
);
|
|
|
|
stmt.run(newUser);
|
|
|
|
return { success: true, message: 'User registered successfully.', user: newUser };
|
|
} catch (error) {
|
|
console.error('Registration error:', error);
|
|
return { success: false, message: 'An unexpected error occurred during registration.' };
|
|
}
|
|
}
|