Files
peworkshop/app/api/register/route.js
T
2025-03-11 23:02:22 +00:00

46 lines
1.2 KiB
JavaScript

import { queryOne, run } from "../../../lib/db";
const bcrypt = require("bcryptjs");
export async function POST(request) {
try {
const { username, password } = await request.json();
// Validate input
if (!username || !password) {
return new Response(
JSON.stringify({ error: "Username and password are required" }),
{ status: 400 }
);
}
// Check if username exists
const existingUser = await queryOne(
"SELECT id FROM users WHERE username = ?",
[username]
);
if (existingUser) {
return new Response(
JSON.stringify({ error: "Username already exists" }),
{ status: 400 }
);
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 10);
// Insert user
await run(
"INSERT INTO users (username, password, role) VALUES (?, ?, 'user')",
[username, hashedPassword]
);
return new Response(JSON.stringify({ success: true }), { status: 201 });
} catch (error) {
console.error("Registration error:", error);
return new Response(JSON.stringify({ error: "Failed to register user" }), {
status: 500,
});
}
}