import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import { randomBytes } from 'crypto';
const JWT_SECRET = process.env.JWT_SECRET;
const JWT_EXPIRES_IN = '7d';
const SALT_ROUNDS = 10;
interface User {
id: string;
email: string;
password: string;
}
async function hashPassword(password: string): Promise<string> {
const salt = await bcrypt.genSalt(SALT_ROUNDS);
return bcrypt.hash(password, salt);
}
async function createUser(email: string, password: string): Promise<{ user: User; token: string }> {
// Check if user already exists
const existingUser = await getUserByEmail(email);
if (existingUser) {
throw new Error('User already exists');
}
// Hash password
const hashedPassword = await hashPassword(password);
// Create user
const user = await saveUser({
id: generateId(),
email,
password: hashedPassword
});
// Generate JWT token
const token = jwt.sign(
{ id: user.id, email: user.email },
JWT_SECRET,
{ expiresIn: JWT_EXPIRES_IN }
);
return { user, token };
}
// Usage in API route
export async function POST(request: Request) {
const { email, password } = await request.json();
const { user, token } = await createUser(email, password);
return Response.json({
success: true,
message: 'Account created successfully',
token,
user: { id: user.id, email: user.email }
});
}