g1t/apps/web/app/routes/workspace/audit-export.ts
| 1 | /** |
| 2 | * The workspace's audit log as a file: `?format=csv` (the default) or |
| 3 | * `json`, with the same filters as the page. Owners get everything; |
| 4 | * members what they may see on the page. |
| 5 | */ |
| 6 | import { data } from "react-router"; |
| 7 | |
| 8 | import type { Route } from "./+types/audit-export"; |
| 9 | import { exportName, parseFilters, toCsv, toQuery } from "../../lib/audit"; |
| 10 | import { auditAll } from "../../lib/audit.server"; |
| 11 | import { requireUser } from "../../lib/session.server"; |
| 12 | |
| 13 | export async function loader({ params, context, request }: Route.LoaderArgs) { |
| 14 | const viewer = requireUser(context, request); |
| 15 | const url = new URL(request.url); |
| 16 | const format = url.searchParams.get("format") === "json" ? "json" : "csv"; |
| 17 | const workspace = params.owner.toLowerCase(); |
| 18 | const filters = parseFilters(url.searchParams); |
| 19 | // The visibility is decided by auditAll; this one is replaced there. |
| 20 | const { visibility: _, ...query } = toQuery(workspace, { kind: "all" }, filters, 500); |
| 21 | const entries = await auditAll(viewer, query); |
| 22 | if (!entries) throw data("Only members of this workspace can read its audit log.", { status: 403 }); |
| 23 | const name = exportName(workspace, format, new Date()); |
| 24 | const headers = { |
| 25 | "content-disposition": `attachment; filename="${name}"`, |
| 26 | "cache-control": "no-store", |
| 27 | }; |
| 28 | return format === "json" |
| 29 | ? new Response(JSON.stringify({ workspace, exportedAt: new Date().toISOString(), entries }, null, 2), { |
| 30 | headers: { ...headers, "content-type": "application/json; charset=utf-8" }, |
| 31 | }) |
| 32 | : new Response(toCsv(entries), { headers: { ...headers, "content-type": "text/csv; charset=utf-8" } }); |
| 33 | } |