Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Create get-own item by id endpoint
  • Loading branch information
regalijan committed Oct 23, 2023
1 parent b453783 commit 5607c2e
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions 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));
}

0 comments on commit 5607c2e

Please sign in to comment.