Update src/app/api/auth/register/route.ts

This commit is contained in:
2026-03-11 20:34:04 +00:00
parent 5267e7757f
commit c4d8f371b4

View File

@@ -1,87 +1,68 @@
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import { hash } from 'bcryptjs';
const DB_FILE = path.join(process.cwd(), 'data', 'users.json');
interface User {
id: string;
name: string;
email: string;
passwordHash: string;
createdAt: string;
}
function ensureDbDirectory() {
const dir = path.dirname(DB_FILE);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
function hashPassword(password: string): string {
return crypto.createHash('sha256').update(password).digest('hex');
}
function getUsers(): User[] {
try {
if (fs.existsSync(DB_FILE)) {
const data = fs.readFileSync(DB_FILE, 'utf-8');
return JSON.parse(data);
}
} catch (error) {
console.error('Error reading users file:', error);
}
return [];
}
function saveUsers(users: User[]) {
ensureDbDirectory();
fs.writeFileSync(DB_FILE, JSON.stringify(users, null, 2));
}
// Temporary in-memory user storage (replace with database)
const users: Map<string, any> = new Map();
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { name, email, password } = body;
const { name, email, password } = await request.json();
// Validation
if (!name || !email || !password) {
return NextResponse.json(
{ message: 'Missing required fields' },
{ message: 'Name, email, and password are required' },
{ status: 400 }
);
}
const users = getUsers();
const existingUser = users.find(u => u.email === email);
if (existingUser) {
if (password.length < 6) {
return NextResponse.json(
{ message: 'Email already registered' },
{ message: 'Password must be at least 6 characters' },
{ status: 400 }
);
}
// Check if user already exists
if (users.has(email)) {
return NextResponse.json(
{ message: 'User already exists' },
{ status: 409 }
);
}
const newUser: User = {
id: crypto.randomUUID(),
// Hash password
const hashedPassword = await hash(password, 10);
// Create user
const user = {
id: Math.random().toString(36).substr(2, 9),
name,
email,
passwordHash: hashPassword(password),
createdAt: new Date().toISOString(),
password: hashedPassword,
createdAt: new Date(),
};
users.push(newUser);
saveUsers(users);
users.set(email, user);
// Create JWT-like token (simplified)
const token = Buffer.from(JSON.stringify({ userId: user.id, email })).toString('base64');
return NextResponse.json(
{ message: 'User registered successfully', userId: newUser.id },
{
message: 'User registered successfully',
token,
user: {
id: user.id,
name: user.name,
email: user.email,
},
},
{ status: 201 }
);
} catch (error) {
console.error('Registration error:', error);
return NextResponse.json(
{ message: 'Internal server error' },
{ message: 'Registration failed' },
{ status: 500 }
);
}