mirror of
https://github.com/fosrl/pangolin.git
synced 2026-01-28 22:00:51 +00:00
Basic table working
This commit is contained in:
@@ -1900,5 +1900,6 @@
|
||||
"action": "Action",
|
||||
"actor": "Actor",
|
||||
"timestamp": "Timestamp",
|
||||
"accessLogs": "Access Logs"
|
||||
"accessLogs": "Access Logs",
|
||||
"exportCsv": "Export CSV"
|
||||
}
|
||||
|
||||
102
server/private/routers/auditLogs/exportActionAuditLog.ts
Normal file
102
server/private/routers/auditLogs/exportActionAuditLog.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
* This file is part of a proprietary work.
|
||||
*
|
||||
* Copyright (c) 2025 Fossorial, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This file is licensed under the Fossorial Commercial License.
|
||||
* You may not use this file except in compliance with the License.
|
||||
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
|
||||
*
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
|
||||
import { actionAuditLog, db } from "@server/db";
|
||||
import { registry } from "@server/openApi";
|
||||
import { NextFunction } from "express";
|
||||
import { Request, Response } from "express";
|
||||
import { eq, gt, lt, and, count } from "drizzle-orm";
|
||||
import { OpenAPITags } from "@server/openApi";
|
||||
import { z } from "zod";
|
||||
import createHttpError from "http-errors";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { QueryActionAuditLogResponse } from "@server/routers/auditLogs/types";
|
||||
import response from "@server/lib/response";
|
||||
import logger from "@server/logger";
|
||||
import { queryAccessAuditLogsParams, queryAccessAuditLogsQuery, querySites } from "./queryActionAuditLog";
|
||||
|
||||
function generateCSV(data: any[]): string {
|
||||
if (data.length === 0) {
|
||||
return "orgId,action,actorType,timestamp,actor\n";
|
||||
}
|
||||
|
||||
const headers = Object.keys(data[0]).join(",");
|
||||
const rows = data.map(row =>
|
||||
Object.values(row).map(value =>
|
||||
typeof value === 'string' && value.includes(',')
|
||||
? `"${value.replace(/"/g, '""')}"`
|
||||
: value
|
||||
).join(",")
|
||||
);
|
||||
|
||||
return [headers, ...rows].join("\n");
|
||||
}
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/org/{orgId}/logs/actionk/export",
|
||||
description: "Export the action audit log for an organization as CSV",
|
||||
tags: [OpenAPITags.Org],
|
||||
request: {
|
||||
query: queryAccessAuditLogsQuery,
|
||||
params: queryAccessAuditLogsParams
|
||||
},
|
||||
responses: {}
|
||||
});
|
||||
|
||||
export async function exportAccessAuditLogs(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedQuery = queryAccessAuditLogsQuery.safeParse(req.query);
|
||||
if (!parsedQuery.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedQuery.error)
|
||||
)
|
||||
);
|
||||
}
|
||||
const { timeStart, timeEnd, limit, offset } = parsedQuery.data;
|
||||
|
||||
const parsedParams = queryAccessAuditLogsParams.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error)
|
||||
)
|
||||
);
|
||||
}
|
||||
const { orgId } = parsedParams.data;
|
||||
|
||||
const baseQuery = querySites(timeStart, timeEnd, orgId);
|
||||
|
||||
const log = await baseQuery.limit(limit).offset(offset);
|
||||
|
||||
const csvData = generateCSV(log);
|
||||
|
||||
res.setHeader('Content-Type', 'text/csv');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="audit-logs-${orgId}-${Date.now()}.csv"`);
|
||||
|
||||
return res.send(csvData);
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,4 +11,5 @@
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
|
||||
export * from "./queryActionAuditLog";
|
||||
export * from "./queryActionAuditLog";
|
||||
export * from "./exportActionAuditLog";
|
||||
@@ -59,7 +59,7 @@ export const queryAccessAuditLogsParams = z.object({
|
||||
orgId: z.string()
|
||||
});
|
||||
|
||||
function querySites(timeStart: number, timeEnd: number, orgId: string) {
|
||||
export function querySites(timeStart: number, timeEnd: number, orgId: string) {
|
||||
return db
|
||||
.select({
|
||||
orgId: actionAuditLog.orgId,
|
||||
@@ -79,6 +79,20 @@ function querySites(timeStart: number, timeEnd: number, orgId: string) {
|
||||
.orderBy(actionAuditLog.timestamp);
|
||||
}
|
||||
|
||||
export function countQuery(timeStart: number, timeEnd: number, orgId: string) {
|
||||
const countQuery = db
|
||||
.select({ count: count() })
|
||||
.from(actionAuditLog)
|
||||
.where(
|
||||
and(
|
||||
gt(actionAuditLog.timestamp, timeStart),
|
||||
lt(actionAuditLog.timestamp, timeEnd),
|
||||
eq(actionAuditLog.orgId, orgId)
|
||||
)
|
||||
);
|
||||
return countQuery;
|
||||
}
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/org/{orgId}/logs/action",
|
||||
@@ -123,18 +137,7 @@ export async function queryAccessAuditLogs(
|
||||
|
||||
const log = await baseQuery.limit(limit).offset(offset);
|
||||
|
||||
const countQuery = db
|
||||
.select({ count: count() })
|
||||
.from(actionAuditLog)
|
||||
.where(
|
||||
and(
|
||||
gt(actionAuditLog.timestamp, timeStart),
|
||||
lt(actionAuditLog.timestamp, timeEnd),
|
||||
eq(actionAuditLog.orgId, orgId)
|
||||
)
|
||||
);
|
||||
|
||||
const totalCountResult = await countQuery;
|
||||
const totalCountResult = await countQuery(timeStart, timeEnd, orgId);
|
||||
const totalCount = totalCountResult[0].count;
|
||||
|
||||
return response<QueryActionAuditLogResponse>(res, {
|
||||
|
||||
@@ -349,4 +349,10 @@ authenticated.post(
|
||||
authenticated.get(
|
||||
"/org/:orgId/logs/action",
|
||||
logs.queryAccessAuditLogs
|
||||
)
|
||||
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/logs/action/export",
|
||||
logs.exportAccessAuditLogs
|
||||
)
|
||||
@@ -21,6 +21,7 @@ export default function GeneralPage() {
|
||||
|
||||
const [rows, setRows] = useState<any[]>([]);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
|
||||
// Set default date range to last 24 hours
|
||||
const getDefaultDateRange = () => {
|
||||
@@ -127,6 +128,40 @@ export default function GeneralPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const exportData = async () => {
|
||||
try {
|
||||
setIsExporting(true);
|
||||
const response = await api.get(`/org/${orgId}/logs/action/export`, {
|
||||
responseType: "blob",
|
||||
params: {
|
||||
timeStart: dateRange.startDate?.date
|
||||
? new Date(dateRange.startDate.date).toISOString()
|
||||
: undefined,
|
||||
timeEnd: dateRange.endDate?.date
|
||||
? new Date(dateRange.endDate.date).toISOString()
|
||||
: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
// Create a URL for the blob and trigger a download
|
||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
const epoch = Math.floor(Date.now() / 1000);
|
||||
link.setAttribute("download", `access_audit_logs_${orgId}_${epoch}.csv`);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.parentNode?.removeChild(link);
|
||||
setIsExporting(false);
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t("error"),
|
||||
description: t("exportError"),
|
||||
variant: "destructive"
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnDef<any>[] = [
|
||||
{
|
||||
accessorKey: "timestamp",
|
||||
@@ -212,6 +247,8 @@ export default function GeneralPage() {
|
||||
searchColumn="action"
|
||||
onRefresh={refreshData}
|
||||
isRefreshing={isRefreshing}
|
||||
onExport={exportData}
|
||||
isExporting={isExporting}
|
||||
onDateRangeChange={handleDateRangeChange}
|
||||
dateRange={{
|
||||
start: dateRange.startDate,
|
||||
@@ -141,7 +141,7 @@ export const orgNavSections = (
|
||||
: []),
|
||||
{
|
||||
title: "sidebarLogs",
|
||||
href: "/{orgId}/settings/logs/access",
|
||||
href: "/{orgId}/settings/logs/action",
|
||||
icon: <Logs className="h-4 w-4" />
|
||||
},
|
||||
{
|
||||
|
||||
@@ -50,7 +50,6 @@ export function DateTimePicker({
|
||||
const handleDateChange = (date: Date | undefined) => {
|
||||
setInternalDate(date);
|
||||
const newValue = { date, time: internalTime };
|
||||
setOpen(false);
|
||||
onChange?.(newValue);
|
||||
};
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ import { Button } from "@app/components/ui/button";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import { DataTablePagination } from "@app/components/DataTablePagination";
|
||||
import { Plus, Search, RefreshCw, Filter, X } from "lucide-react";
|
||||
import { Plus, Search, RefreshCw, Filter, X, Download } from "lucide-react";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
@@ -82,6 +82,8 @@ type DataTableProps<TData, TValue> = {
|
||||
title?: string;
|
||||
addButtonText?: string;
|
||||
onRefresh?: () => void;
|
||||
onExport?: () => void;
|
||||
isExporting?: boolean;
|
||||
isRefreshing?: boolean;
|
||||
searchPlaceholder?: string;
|
||||
searchColumn?: string;
|
||||
@@ -109,6 +111,8 @@ export function LogDataTable<TData, TValue>({
|
||||
title,
|
||||
onRefresh,
|
||||
isRefreshing,
|
||||
onExport,
|
||||
isExporting,
|
||||
searchPlaceholder = "Search...",
|
||||
searchColumn = "name",
|
||||
defaultSort,
|
||||
@@ -142,7 +146,6 @@ export function LogDataTable<TData, TValue>({
|
||||
defaultTab || tabs?.[0]?.id || ""
|
||||
);
|
||||
|
||||
const [showDatePicker, setShowDatePicker] = useState(false);
|
||||
const [startDate, setStartDate] = useState<DateTimeValue>(
|
||||
dateRange?.start || {}
|
||||
);
|
||||
@@ -233,22 +236,11 @@ export function LogDataTable<TData, TValue>({
|
||||
onDateRangeChange?.(start, end);
|
||||
};
|
||||
|
||||
const clearDateFilter = () => {
|
||||
const emptyStart = {};
|
||||
const emptyEnd = {};
|
||||
setStartDate(emptyStart);
|
||||
setEndDate(emptyEnd);
|
||||
onDateRangeChange?.(emptyStart, emptyEnd);
|
||||
setShowDatePicker(false);
|
||||
};
|
||||
|
||||
const hasDateFilter = startDate?.date || endDate?.date;
|
||||
|
||||
return (
|
||||
<div className="container mx-auto max-w-12xl">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-col space-y-4 sm:flex-row sm:items-center sm:justify-between sm:space-y-0 pb-4">
|
||||
<div className="flex flex-row space-y-3 w-full sm:mr-2 gap-2">
|
||||
<div className="flex flex-row items-start w-full sm:mr-2 gap-2">
|
||||
<div className="relative w-full sm:max-w-sm">
|
||||
<Input
|
||||
placeholder={searchPlaceholder}
|
||||
@@ -258,30 +250,10 @@ export function LogDataTable<TData, TValue>({
|
||||
String(e.target.value)
|
||||
)
|
||||
}
|
||||
className="w-full pl-8"
|
||||
className="w-full pl-8 m-0"
|
||||
/>
|
||||
<Search className="h-4 w-4 absolute left-2 top-1/2 transform -translate-y-1/2 text-muted-foreground" />
|
||||
</div>
|
||||
{tabs && tabs.length > 0 && (
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={handleTabChange}
|
||||
className="w-full"
|
||||
>
|
||||
<TabsList>
|
||||
{tabs.map((tab) => (
|
||||
<TabsTrigger
|
||||
key={tab.id}
|
||||
value={tab.id}
|
||||
>
|
||||
{tab.label} (
|
||||
{data.filter(tab.filterFn).length})
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
)}
|
||||
|
||||
<DateRangePicker
|
||||
startValue={startDate}
|
||||
endValue={endDate}
|
||||
@@ -289,7 +261,7 @@ export function LogDataTable<TData, TValue>({
|
||||
className="flex-wrap gap-2"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 sm:justify-end">
|
||||
<div className="flex items-start gap-2 sm:justify-end">
|
||||
{onRefresh && (
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -302,6 +274,18 @@ export function LogDataTable<TData, TValue>({
|
||||
{t("refresh")}
|
||||
</Button>
|
||||
)}
|
||||
{onExport && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onExport}
|
||||
disabled={isExporting}
|
||||
>
|
||||
<Download
|
||||
className={`mr-2 h-4 w-4 ${isExporting ? "animate-spin" : ""}`}
|
||||
/>
|
||||
{t("exportCsv")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
||||
Reference in New Issue
Block a user