feat: midterm shit done
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import { createErrorResponse } from '../utils';
|
||||
|
||||
export async function onRequestPost(context) {
|
||||
try {
|
||||
const { request, env } = context;
|
||||
|
||||
const { username, password } = await request.json();
|
||||
|
||||
if (!username || !password) {
|
||||
return createErrorResponse("Missing username or password", 400);
|
||||
}
|
||||
|
||||
if (username.length < 3) {
|
||||
return createErrorResponse("Username must be at least 3 characters", 400);
|
||||
}
|
||||
|
||||
if (password.length < 8) {
|
||||
return createErrorResponse("Password must be at least 8 characters", 400);
|
||||
}
|
||||
|
||||
if (!/^[a-zA-Z0-9]+$/.test(username)) {
|
||||
return createErrorResponse("Username must be alphanumeric", 400);
|
||||
}
|
||||
|
||||
// Check if the username already exists
|
||||
const { results: existingUsers } = await env.DB.prepare("SELECT id FROM users WHERE username = ?").bind(username).all();
|
||||
if (existingUsers.length > 0) {
|
||||
return createErrorResponse("Username already exists", 400);
|
||||
}
|
||||
|
||||
// Store the username and password in D1
|
||||
await env.DB.prepare("INSERT INTO users (username, password, avatar) VALUES (?, ?, ?)").bind(username, password, "avatars/default.png").run();
|
||||
|
||||
// Get the user ID
|
||||
const { results } = await env.DB.prepare("SELECT id FROM users WHERE username = ?").bind(username).all();
|
||||
const userId = results[0].id;
|
||||
|
||||
// Registration successful, return success response
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: "Registration successful. Please login.",
|
||||
}),
|
||||
{
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Registration error:", error);
|
||||
return createErrorResponse("Server Error", 500);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user