From 5607c2eea1521108f4c5da54fb0b81e675cd3e14 Mon Sep 17 00:00:00 2001 From: Regalijan Date: Sun, 22 Oct 2023 22:33:23 -0400 Subject: [PATCH] Create get-own item by id endpoint --- functions/api/me/items/[type]/[id].ts | 70 +++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 functions/api/me/items/[type]/[id].ts diff --git a/functions/api/me/items/[type]/[id].ts b/functions/api/me/items/[type]/[id].ts new file mode 100644 index 0000000..8c82bf2 --- /dev/null +++ b/functions/api/me/items/[type]/[id].ts @@ -0,0 +1,70 @@ +import { jsonError, jsonResponse } from "../../../../common.js"; + +export async function onRequestGet(context: RequestContext) { + const { id, type } = context.params; + + if (!["appeal", "inactivity", "report"].includes(type as string)) + return jsonError("Invalid type", 400); + + const data = (await context.env.DATA.get(`${type}_${id}`, { + type: "json", + })) as { + created_at: number; + id: string; + open: boolean; + user?: { id: string; username: string }; + } & { [k: string]: any }; + + if (type === "report") { + let resolvedUrls = []; + let signingPromises = []; + const key = await crypto.subtle.importKey( + "raw", + Uint8Array.from(atob(context.env.URL_SIGNING_KEY), (c) => + c.charCodeAt(0), + ), + { hash: "SHA=256", name: "HMAC" }, + false, + ["sign"], + ); + + const exp = Math.round(Date.now() / 1000) + 1800; + + for (const attachment of data.attachments) { + const unsignedUrl = `https://mediaproxy.carcrushers.cc/${attachment}?Expires=${exp}&KeyName=portal-media-linkgen`; + signingPromises.push( + crypto.subtle.sign("HMAC", key, new TextEncoder().encode(unsignedUrl)), + ); + } + + let signatures: ArrayBuffer[]; + + try { + signatures = await Promise.all(signingPromises); + } catch (e) { + console.log(e); + + return jsonError("Failed to create signed links", 500); + } + + for (let i = 0; i < signatures.length; i++) { + resolvedUrls.push( + `https://mediaproxy.carcrushers.cc/${ + data.attachments[i] + }?Expires=${exp}&KeyName=portal-media-linkgen&Signature=${btoa( + String.fromCharCode(...new Uint8Array(signatures[i])) + .replaceAll("+", "-") + .replaceAll("/", "_") + .replaceAll("=", ""), + )}`, + ); + } + + data.resolved_attachments = resolvedUrls; + } + + if (!data?.user?.id !== context.data.current_user.id) + return jsonError("Item does not exist", 404); + + return jsonResponse(JSON.stringify(data)); +}