Switch to version 3: remove src/app/api/auth/register/route.ts
This commit is contained in:
@@ -1,88 +0,0 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { name, email, password } = body;
|
||||
|
||||
if (!name || !email || !password) {
|
||||
return NextResponse.json(
|
||||
{ message: 'Missing required fields' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const users = getUsers();
|
||||
const existingUser = users.find(u => u.email === email);
|
||||
|
||||
if (existingUser) {
|
||||
return NextResponse.json(
|
||||
{ message: 'Email already registered' },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
const newUser: User = {
|
||||
id: crypto.randomUUID(),
|
||||
name,
|
||||
email,
|
||||
passwordHash: hashPassword(password),
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
users.push(newUser);
|
||||
saveUsers(users);
|
||||
|
||||
return NextResponse.json(
|
||||
{ message: 'User registered successfully', userId: newUser.id },
|
||||
{ status: 201 }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Registration error:', error);
|
||||
return NextResponse.json(
|
||||
{ message: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user