From bd50acfe1d1c0de5370eadd60af2df3255fada82 Mon Sep 17 00:00:00 2001 From: Regalijan Date: Sun, 20 Oct 2024 03:00:56 -0400 Subject: [PATCH] Enforce n - 1 deletion requirement server side --- functions/api/events-team/events/[id].ts | 30 ++++++++++++++++++------ 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/functions/api/events-team/events/[id].ts b/functions/api/events-team/events/[id].ts index f8a95d8..66189b5 100644 --- a/functions/api/events-team/events/[id].ts +++ b/functions/api/events-team/events/[id].ts @@ -2,8 +2,12 @@ import { jsonError } from "../../../common.js"; export async function onRequestDelete(context: RequestContext) { const eventId = context.params.id as string; - const eventData = await context.env.D1.prepare( - "SELECT created_by FROM events WHERE id = ?;", + const eventData: + | ({ + [k: string]: number; + } & { created_by: string }) + | null = await context.env.D1.prepare( + "SELECT created_by, day, month, year FROM events WHERE id = ?;", ) .bind(eventId) .first(); @@ -11,14 +15,26 @@ export async function onRequestDelete(context: RequestContext) { if (!eventData) return jsonError("No event exists with that ID", 404); const { current_user: currentUser } = context.data; + const isETM = [1 << 4, 1 << 12].find((int) => currentUser.permissions & int); - if ( - eventData.created_by !== currentUser.id && - ![1 << 4, 1 << 12].find((int) => currentUser.permissions & int) - ) + if (eventData.created_by !== currentUser.id && !isETM) return jsonError("You are not authorized to delete that event", 403); - await context.env.DATA.delete(`event_${eventId}`); + const now = new Date(); + now.setUTCHours(0, 0, 0, 0); + + const eventDate = new Date( + eventData.year, + eventData.month - 1, + eventData.day, + ); + + if (!isETM && now.getTime() <= eventDate.getTime()) + return jsonError( + "Event cannot be deleted on or after the scheduled date", + 403, + ); + await context.env.D1.prepare("DELETE FROM events WHERE id = ?;") .bind(eventId) .run();