feat: hcaptcha

This commit is contained in:
Tony Yang
2025-04-15 14:46:16 +08:00
parent b8ae97e49b
commit 1b60b3517d
20 changed files with 430 additions and 247 deletions
+41 -25
View File
@@ -1,5 +1,6 @@
import { verifyJWT } from '../middleware/auth';
import { createErrorResponse, createSuccessResponse } from '../utils';
import hCaptchaPlugin from "@cloudflare/pages-plugin-hcaptcha";
export async function onRequestGet(context) {
try {
@@ -15,42 +16,57 @@ export async function onRequestGet(context) {
}
}
export async function onRequestPost(context) {
try {
const { request, env } = context;
export const onRequestPost = [
async (context) => {
return hCaptchaPlugin({
secret: context.env.hcaptcha_secret_key,
sitekey: context.env.hcaptcha_site_key,
onError: (context) => {
console.error("hCaptcha error:", context.error);
return createErrorResponse("hCaptcha verification failed", 403);
}
})(context);
},
async (context) => {
try {
const { request, env } = context;
let payload;
// Verify the JWT token
const authResult = await verifyJWT(context);
if (authResult) {
return authResult; // Return the error response from the middleware
}
try {
const formData = await request.formData();
payload = JSON.parse(formData.get('payload'));
} catch (e) {
console.error("Payload parsing error:", e);
return createErrorResponse("Invalid payload", 400);
}
const { message } = await request.json();
const { message } = payload;
if (!message) {
return createErrorResponse("Empty message", 400);
}
if (!message) {
return createErrorResponse("Empty message", 400);
}
if (message.length > 200) {
return createErrorResponse("Message too long", 400);
}
if (message.length > 200) {
return createErrorResponse("Message too long", 400);
}
// Generate a unique ID for the message
const messageId = crypto.randomUUID();
// Generate a unique ID for the message
const messageId = crypto.randomUUID();
// Store the message in D1
await env.DB.prepare("INSERT INTO messages (id, userId, message) VALUES (?, ?, ?)")
.bind(messageId, context.user.userId, message)
.run();
// Store the message in D1
await env.DB.prepare("INSERT INTO messages (id, userId, message) VALUES (?, ?, ?)")
.bind(messageId, context.user.userId, message)
.run();
return new Response(JSON.stringify({ id: messageId, username: context.user.username, message }), {
headers: { 'Content-Type': 'application/json' },
});
return new Response(JSON.stringify({ id: messageId, username: context.user.username, message }), {
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
console.error("Message posting error:", error);
return createErrorResponse("Message posting failed", 500);
}
}
},
];
export async function onRequestDelete(context) {
try {