69 lines
2.1 KiB
TypeScript

import { jsonError, jsonResponse } from "../../common.js";
export async function onRequestGet(context: RequestContext) {
const { searchParams } = new URL(context.request.url);
const before = parseInt(searchParams.get("before") || `${Date.now()}`);
const entryType = searchParams.get("type");
const showClosed = searchParams.get("showClosed") === "true";
const tables: { [k: string]: string } = {
appeal: "appeals",
gma: "game_appeals",
report: "reports",
};
const types: { [k: string]: string } = {
appeal: "appeal",
gma: "gameappeal",
report: "report",
};
const permissions: { [k: string]: number[] } = {
appeal: [1 << 0, 1 << 1],
gma: [1 << 5],
report: [1 << 5],
};
const { current_user: currentUser } = context.data;
if (!entryType || !types[entryType])
return jsonError("Invalid filter type", 400);
if (!permissions[entryType].find((p) => currentUser.permissions & p))
return jsonError("You cannot use this filter", 403);
if (isNaN(before) || before > Date.now())
return jsonError("Invalid `before` parameter", 400);
const prefix = types[entryType];
const table = tables[entryType];
const items = [];
const { results }: { results?: { created_at: number; id: string }[] } =
/*
This is normally VERY BAD and can lead to injection attacks
However, there is no other way to do this, as using bindings for table names is unsupported apparently
To avoid any potential injection attacks we enforce a list of specific values and permissions for table names
*/
await context.env.D1.prepare(
`SELECT id
FROM ${table}
WHERE created_at < ? AND open = ?
ORDER BY created_at DESC LIMIT 25;`,
)
.bind(before, Number(!showClosed))
.all();
if (results)
for (const { id } of results) {
const item: { [k: string]: any } | null = await context.env.DATA.get(
`${prefix}_${id}`,
{
type: "json",
},
);
if (item) {
delete item.user?.email;
items.push({ ...item, id });
}
}
return jsonResponse(JSON.stringify(items.filter((v) => v !== null)));
}