mirror of
https://github.com/fosrl/pangolin.git
synced 2026-03-07 03:06:40 +00:00
Basic request log working
This commit is contained in:
@@ -1902,5 +1902,23 @@
|
|||||||
"timestamp": "Timestamp",
|
"timestamp": "Timestamp",
|
||||||
"accessLogs": "Access Logs",
|
"accessLogs": "Access Logs",
|
||||||
"exportCsv": "Export CSV",
|
"exportCsv": "Export CSV",
|
||||||
"actorId": "Actor ID"
|
"actorId": "Actor ID",
|
||||||
|
"allowedByRule": "Allowed by Rule",
|
||||||
|
"allowedNoAuth": "Allowed No Auth",
|
||||||
|
"validAccessToken": "Valid Access Token",
|
||||||
|
"validHeaderAuth": "Valid header auth",
|
||||||
|
"validPincode": "Valid Pincode",
|
||||||
|
"validPassword": "Valid Password",
|
||||||
|
"validEmail": "Valid email",
|
||||||
|
"validSSO": "Valid SSO",
|
||||||
|
"resourceBlocked": "Resource Blocked",
|
||||||
|
"droppedByRule": "Dropped by Rule",
|
||||||
|
"noSessions": "No Sessions",
|
||||||
|
"temporaryRequestToken": "Temporary Request Token",
|
||||||
|
"noMoreAuthMethods": "No More Auth Methods",
|
||||||
|
"ip": "IP Address",
|
||||||
|
"reason": "Reason",
|
||||||
|
"requestLogs": "Request Logs",
|
||||||
|
"host": "Host",
|
||||||
|
"location": "Location"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,24 +24,8 @@ import { fromError } from "zod-validation-error";
|
|||||||
import { QueryActionAuditLogResponse } from "@server/routers/auditLogs/types";
|
import { QueryActionAuditLogResponse } from "@server/routers/auditLogs/types";
|
||||||
import response from "@server/lib/response";
|
import response from "@server/lib/response";
|
||||||
import logger from "@server/logger";
|
import logger from "@server/logger";
|
||||||
import { queryAccessAuditLogsParams, queryAccessAuditLogsQuery, querySites } from "./queryActionAuditLog";
|
import { queryActionAuditLogsParams, queryActionAuditLogsQuery, querySites } from "./queryActionAuditLog";
|
||||||
|
import { generateCSV } from "@server/routers/auditLogs/generateCSV";
|
||||||
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({
|
registry.registerPath({
|
||||||
method: "get",
|
method: "get",
|
||||||
@@ -49,19 +33,19 @@ registry.registerPath({
|
|||||||
description: "Export the action audit log for an organization as CSV",
|
description: "Export the action audit log for an organization as CSV",
|
||||||
tags: [OpenAPITags.Org],
|
tags: [OpenAPITags.Org],
|
||||||
request: {
|
request: {
|
||||||
query: queryAccessAuditLogsQuery,
|
query: queryActionAuditLogsQuery,
|
||||||
params: queryAccessAuditLogsParams
|
params: queryActionAuditLogsParams
|
||||||
},
|
},
|
||||||
responses: {}
|
responses: {}
|
||||||
});
|
});
|
||||||
|
|
||||||
export async function exportAccessAuditLogs(
|
export async function exportActionAuditLogs(
|
||||||
req: Request,
|
req: Request,
|
||||||
res: Response,
|
res: Response,
|
||||||
next: NextFunction
|
next: NextFunction
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
try {
|
try {
|
||||||
const parsedQuery = queryAccessAuditLogsQuery.safeParse(req.query);
|
const parsedQuery = queryActionAuditLogsQuery.safeParse(req.query);
|
||||||
if (!parsedQuery.success) {
|
if (!parsedQuery.success) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(
|
createHttpError(
|
||||||
@@ -72,7 +56,7 @@ export async function exportAccessAuditLogs(
|
|||||||
}
|
}
|
||||||
const { timeStart, timeEnd, limit, offset } = parsedQuery.data;
|
const { timeStart, timeEnd, limit, offset } = parsedQuery.data;
|
||||||
|
|
||||||
const parsedParams = queryAccessAuditLogsParams.safeParse(req.params);
|
const parsedParams = queryActionAuditLogsParams.safeParse(req.params);
|
||||||
if (!parsedParams.success) {
|
if (!parsedParams.success) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(
|
createHttpError(
|
||||||
@@ -90,7 +74,7 @@ export async function exportAccessAuditLogs(
|
|||||||
const csvData = generateCSV(log);
|
const csvData = generateCSV(log);
|
||||||
|
|
||||||
res.setHeader('Content-Type', 'text/csv');
|
res.setHeader('Content-Type', 'text/csv');
|
||||||
res.setHeader('Content-Disposition', `attachment; filename="audit-logs-${orgId}-${Date.now()}.csv"`);
|
res.setHeader('Content-Disposition', `attachment; filename="action-audit-logs-${orgId}-${Date.now()}.csv"`);
|
||||||
|
|
||||||
return res.send(csvData);
|
return res.send(csvData);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ import { QueryActionAuditLogResponse } from "@server/routers/auditLogs/types";
|
|||||||
import response from "@server/lib/response";
|
import response from "@server/lib/response";
|
||||||
import logger from "@server/logger";
|
import logger from "@server/logger";
|
||||||
|
|
||||||
export const queryAccessAuditLogsQuery = z.object({
|
export const queryActionAuditLogsQuery = z.object({
|
||||||
// iso string just validate its a parseable date
|
// iso string just validate its a parseable date
|
||||||
timeStart: z
|
timeStart: z
|
||||||
.string()
|
.string()
|
||||||
@@ -55,7 +55,7 @@ export const queryAccessAuditLogsQuery = z.object({
|
|||||||
.pipe(z.number().int().nonnegative())
|
.pipe(z.number().int().nonnegative())
|
||||||
});
|
});
|
||||||
|
|
||||||
export const queryAccessAuditLogsParams = z.object({
|
export const queryActionAuditLogsParams = z.object({
|
||||||
orgId: z.string()
|
orgId: z.string()
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -100,19 +100,19 @@ registry.registerPath({
|
|||||||
description: "Query the action audit log for an organization",
|
description: "Query the action audit log for an organization",
|
||||||
tags: [OpenAPITags.Org],
|
tags: [OpenAPITags.Org],
|
||||||
request: {
|
request: {
|
||||||
query: queryAccessAuditLogsQuery,
|
query: queryActionAuditLogsQuery,
|
||||||
params: queryAccessAuditLogsParams
|
params: queryActionAuditLogsParams
|
||||||
},
|
},
|
||||||
responses: {}
|
responses: {}
|
||||||
});
|
});
|
||||||
|
|
||||||
export async function queryAccessAuditLogs(
|
export async function queryActionAuditLogs(
|
||||||
req: Request,
|
req: Request,
|
||||||
res: Response,
|
res: Response,
|
||||||
next: NextFunction
|
next: NextFunction
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
try {
|
try {
|
||||||
const parsedQuery = queryAccessAuditLogsQuery.safeParse(req.query);
|
const parsedQuery = queryActionAuditLogsQuery.safeParse(req.query);
|
||||||
if (!parsedQuery.success) {
|
if (!parsedQuery.success) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(
|
createHttpError(
|
||||||
@@ -123,7 +123,7 @@ export async function queryAccessAuditLogs(
|
|||||||
}
|
}
|
||||||
const { timeStart, timeEnd, limit, offset } = parsedQuery.data;
|
const { timeStart, timeEnd, limit, offset } = parsedQuery.data;
|
||||||
|
|
||||||
const parsedParams = queryAccessAuditLogsParams.safeParse(req.params);
|
const parsedParams = queryActionAuditLogsParams.safeParse(req.params);
|
||||||
if (!parsedParams.success) {
|
if (!parsedParams.success) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(
|
createHttpError(
|
||||||
|
|||||||
@@ -348,11 +348,11 @@ authenticated.post(
|
|||||||
|
|
||||||
authenticated.get(
|
authenticated.get(
|
||||||
"/org/:orgId/logs/action",
|
"/org/:orgId/logs/action",
|
||||||
logs.queryAccessAuditLogs
|
logs.queryActionAuditLogs
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
authenticated.get(
|
authenticated.get(
|
||||||
"/org/:orgId/logs/action/export",
|
"/org/:orgId/logs/action/export",
|
||||||
logs.exportAccessAuditLogs
|
logs.exportActionAuditLogs
|
||||||
)
|
)
|
||||||
73
server/routers/auditLogs/exportRequstAuditLog.ts
Normal file
73
server/routers/auditLogs/exportRequstAuditLog.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import { db, requestAuditLog } 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 { QueryRequestAuditLogResponse } from "@server/routers/auditLogs/types";
|
||||||
|
import response from "@server/lib/response";
|
||||||
|
import logger from "@server/logger";
|
||||||
|
import { queryAccessAuditLogsQuery, queryRequestAuditLogsParams, querySites } from "./queryRequstAuditLog";
|
||||||
|
import { generateCSV } from "./generateCSV";
|
||||||
|
|
||||||
|
registry.registerPath({
|
||||||
|
method: "get",
|
||||||
|
path: "/org/{orgId}/logs/request",
|
||||||
|
description: "Query the request audit log for an organization",
|
||||||
|
tags: [OpenAPITags.Org],
|
||||||
|
request: {
|
||||||
|
query: queryAccessAuditLogsQuery,
|
||||||
|
params: queryRequestAuditLogsParams
|
||||||
|
},
|
||||||
|
responses: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function exportRequestAuditLogs(
|
||||||
|
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 = queryRequestAuditLogsParams.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="request-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")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
16
server/routers/auditLogs/generateCSV.ts
Normal file
16
server/routers/auditLogs/generateCSV.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
export 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");
|
||||||
|
}
|
||||||
2
server/routers/auditLogs/index.ts
Normal file
2
server/routers/auditLogs/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export * from "./queryRequstAuditLog";
|
||||||
|
export * from "./exportRequstAuditLog";
|
||||||
165
server/routers/auditLogs/queryRequstAuditLog.ts
Normal file
165
server/routers/auditLogs/queryRequstAuditLog.ts
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
import { db, requestAuditLog } 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 { QueryRequestAuditLogResponse } from "@server/routers/auditLogs/types";
|
||||||
|
import response from "@server/lib/response";
|
||||||
|
import logger from "@server/logger";
|
||||||
|
|
||||||
|
export const queryAccessAuditLogsQuery = z.object({
|
||||||
|
// iso string just validate its a parseable date
|
||||||
|
timeStart: z
|
||||||
|
.string()
|
||||||
|
.refine((val) => !isNaN(Date.parse(val)), {
|
||||||
|
message: "timeStart must be a valid ISO date string"
|
||||||
|
})
|
||||||
|
.transform((val) => Math.floor(new Date(val).getTime() / 1000)),
|
||||||
|
timeEnd: z
|
||||||
|
.string()
|
||||||
|
.refine((val) => !isNaN(Date.parse(val)), {
|
||||||
|
message: "timeEnd must be a valid ISO date string"
|
||||||
|
})
|
||||||
|
.transform((val) => Math.floor(new Date(val).getTime() / 1000))
|
||||||
|
.optional()
|
||||||
|
.default(new Date().toISOString()),
|
||||||
|
limit: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.default("1000")
|
||||||
|
.transform(Number)
|
||||||
|
.pipe(z.number().int().positive()),
|
||||||
|
offset: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.default("0")
|
||||||
|
.transform(Number)
|
||||||
|
.pipe(z.number().int().nonnegative())
|
||||||
|
});
|
||||||
|
|
||||||
|
export const queryRequestAuditLogsParams = z.object({
|
||||||
|
orgId: z.string()
|
||||||
|
});
|
||||||
|
|
||||||
|
export function querySites(timeStart: number, timeEnd: number, orgId: string) {
|
||||||
|
return db
|
||||||
|
.select({
|
||||||
|
timestamp: requestAuditLog.timestamp,
|
||||||
|
orgId: requestAuditLog.orgId,
|
||||||
|
action: requestAuditLog.action,
|
||||||
|
reason: requestAuditLog.reason,
|
||||||
|
actorType: requestAuditLog.actorType,
|
||||||
|
actor: requestAuditLog.actor,
|
||||||
|
actorId: requestAuditLog.actorId,
|
||||||
|
resourceId: requestAuditLog.resourceId,
|
||||||
|
ip: requestAuditLog.ip,
|
||||||
|
location: requestAuditLog.location,
|
||||||
|
userAgent: requestAuditLog.userAgent,
|
||||||
|
metadata: requestAuditLog.metadata,
|
||||||
|
headers: requestAuditLog.headers,
|
||||||
|
query: requestAuditLog.query,
|
||||||
|
originalRequestURL: requestAuditLog.originalRequestURL,
|
||||||
|
scheme: requestAuditLog.scheme,
|
||||||
|
host: requestAuditLog.host,
|
||||||
|
path: requestAuditLog.path,
|
||||||
|
method: requestAuditLog.method,
|
||||||
|
tls: requestAuditLog.tls,
|
||||||
|
})
|
||||||
|
.from(requestAuditLog)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
gt(requestAuditLog.timestamp, timeStart),
|
||||||
|
lt(requestAuditLog.timestamp, timeEnd),
|
||||||
|
eq(requestAuditLog.orgId, orgId)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.orderBy(requestAuditLog.timestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function countQuery(timeStart: number, timeEnd: number, orgId: string) {
|
||||||
|
const countQuery = db
|
||||||
|
.select({ count: count() })
|
||||||
|
.from(requestAuditLog)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
gt(requestAuditLog.timestamp, timeStart),
|
||||||
|
lt(requestAuditLog.timestamp, timeEnd),
|
||||||
|
eq(requestAuditLog.orgId, orgId)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return countQuery;
|
||||||
|
}
|
||||||
|
|
||||||
|
registry.registerPath({
|
||||||
|
method: "get",
|
||||||
|
path: "/org/{orgId}/logs/request",
|
||||||
|
description: "Query the request audit log for an organization",
|
||||||
|
tags: [OpenAPITags.Org],
|
||||||
|
request: {
|
||||||
|
query: queryAccessAuditLogsQuery,
|
||||||
|
params: queryRequestAuditLogsParams
|
||||||
|
},
|
||||||
|
responses: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function queryRequestAuditLogs(
|
||||||
|
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 = queryRequestAuditLogsParams.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 totalCountResult = await countQuery(timeStart, timeEnd, orgId);
|
||||||
|
const totalCount = totalCountResult[0].count;
|
||||||
|
|
||||||
|
return response<QueryRequestAuditLogResponse>(res, {
|
||||||
|
data: {
|
||||||
|
log: log,
|
||||||
|
pagination: {
|
||||||
|
total: totalCount,
|
||||||
|
limit,
|
||||||
|
offset
|
||||||
|
}
|
||||||
|
},
|
||||||
|
success: true,
|
||||||
|
error: false,
|
||||||
|
message: "Action audit logs retrieved successfully",
|
||||||
|
status: HttpCode.OK
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(error);
|
||||||
|
return next(
|
||||||
|
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ export type QueryActionAuditLogResponse = {
|
|||||||
orgId: string;
|
orgId: string;
|
||||||
action: string;
|
action: string;
|
||||||
actorType: string;
|
actorType: string;
|
||||||
|
actorId: string;
|
||||||
timestamp: number;
|
timestamp: number;
|
||||||
actor: string;
|
actor: string;
|
||||||
}[];
|
}[];
|
||||||
@@ -12,3 +13,33 @@ export type QueryActionAuditLogResponse = {
|
|||||||
offset: number;
|
offset: number;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type QueryRequestAuditLogResponse = {
|
||||||
|
log: {
|
||||||
|
timestamp: number;
|
||||||
|
orgId: string;
|
||||||
|
action: boolean;
|
||||||
|
reason: number;
|
||||||
|
actorType: string | null;
|
||||||
|
actor: string | null;
|
||||||
|
actorId: string | null;
|
||||||
|
resourceId: number | null;
|
||||||
|
ip: string | null;
|
||||||
|
location: string | null;
|
||||||
|
userAgent: string | null;
|
||||||
|
metadata: string | null;
|
||||||
|
headers: string | null;
|
||||||
|
query: string | null;
|
||||||
|
originalRequestURL: string | null;
|
||||||
|
scheme: string | null;
|
||||||
|
host: string | null;
|
||||||
|
path: string | null;
|
||||||
|
method: string | null;
|
||||||
|
tls: boolean | null;
|
||||||
|
}[];
|
||||||
|
pagination: {
|
||||||
|
total: number;
|
||||||
|
limit: number;
|
||||||
|
offset: number;
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -69,7 +69,7 @@ export async function logRequestAudit(
|
|||||||
|
|
||||||
if (!orgId) {
|
if (!orgId) {
|
||||||
logger.warn("logRequestAudit: No organization context found");
|
logger.warn("logRequestAudit: No organization context found");
|
||||||
orgId = "unknown";
|
orgId = "org_7g93l5xu7p61q14";
|
||||||
// return;
|
// return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,6 +85,26 @@ export async function logRequestAudit(
|
|||||||
metadata = JSON.stringify(metadata);
|
metadata = JSON.stringify(metadata);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const clientIp = body.requestIp
|
||||||
|
? (() => {
|
||||||
|
if (body.requestIp.startsWith("[") && body.requestIp.includes("]")) {
|
||||||
|
// if brackets are found, extract the IPv6 address from between the brackets
|
||||||
|
const ipv6Match = body.requestIp.match(/\[(.*?)\]/);
|
||||||
|
if (ipv6Match) {
|
||||||
|
return ipv6Match[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ivp4
|
||||||
|
// split at last colon
|
||||||
|
const lastColonIndex = body.requestIp.lastIndexOf(":");
|
||||||
|
if (lastColonIndex !== -1) {
|
||||||
|
return body.requestIp.substring(0, lastColonIndex);
|
||||||
|
}
|
||||||
|
return body.requestIp;
|
||||||
|
})()
|
||||||
|
: undefined;
|
||||||
|
|
||||||
await db.insert(requestAuditLog).values({
|
await db.insert(requestAuditLog).values({
|
||||||
timestamp,
|
timestamp,
|
||||||
orgId,
|
orgId,
|
||||||
@@ -104,7 +124,7 @@ export async function logRequestAudit(
|
|||||||
host: body.host,
|
host: body.host,
|
||||||
path: body.path,
|
path: body.path,
|
||||||
method: body.method,
|
method: body.method,
|
||||||
ip: body.requestIp,
|
ip: clientIp,
|
||||||
tls: body.tls
|
tls: body.tls
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import * as supporterKey from "./supporterKey";
|
|||||||
import * as accessToken from "./accessToken";
|
import * as accessToken from "./accessToken";
|
||||||
import * as idp from "./idp";
|
import * as idp from "./idp";
|
||||||
import * as apiKeys from "./apiKeys";
|
import * as apiKeys from "./apiKeys";
|
||||||
|
import * as logs from "./auditLogs";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import {
|
import {
|
||||||
verifyAccessTokenAccess,
|
verifyAccessTokenAccess,
|
||||||
@@ -1180,3 +1181,13 @@ authRouter.delete(
|
|||||||
}),
|
}),
|
||||||
auth.deleteSecurityKey
|
auth.deleteSecurityKey
|
||||||
);
|
);
|
||||||
|
|
||||||
|
authenticated.get(
|
||||||
|
"/org/:orgId/logs/request",
|
||||||
|
logs.queryRequestAuditLogs
|
||||||
|
)
|
||||||
|
|
||||||
|
authenticated.get(
|
||||||
|
"/org/:orgId/logs/request/export",
|
||||||
|
logs.exportRequestAuditLogs
|
||||||
|
)
|
||||||
@@ -190,7 +190,7 @@ export default function GeneralPage() {
|
|||||||
const epoch = Math.floor(Date.now() / 1000);
|
const epoch = Math.floor(Date.now() / 1000);
|
||||||
link.setAttribute(
|
link.setAttribute(
|
||||||
"download",
|
"download",
|
||||||
`access_audit_logs_${orgId}_${epoch}.csv`
|
`access-audit-logs-${orgId}-${epoch}.csv`
|
||||||
);
|
);
|
||||||
document.body.appendChild(link);
|
document.body.appendChild(link);
|
||||||
link.click();
|
link.click();
|
||||||
@@ -274,8 +274,8 @@ export default function GeneralPage() {
|
|||||||
<LogDataTable
|
<LogDataTable
|
||||||
columns={columns}
|
columns={columns}
|
||||||
data={rows}
|
data={rows}
|
||||||
persistPageSize="access-logs-table"
|
persistPageSize="action-logs-table"
|
||||||
title={t("accessLogs")}
|
title={t("actionLogs")}
|
||||||
searchPlaceholder={t("searchLogs")}
|
searchPlaceholder={t("searchLogs")}
|
||||||
searchColumn="action"
|
searchColumn="action"
|
||||||
onRefresh={refreshData}
|
onRefresh={refreshData}
|
||||||
|
|||||||
@@ -34,12 +34,12 @@ export default async function GeneralSettingsPage({
|
|||||||
|
|
||||||
const navItems = [
|
const navItems = [
|
||||||
{
|
{
|
||||||
title: t("action"),
|
|
||||||
href: `/{orgId}/settings/logs/action`
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: t("request"),
|
title: t("request"),
|
||||||
href: `/{orgId}/settings/logs/request`
|
href: `/{orgId}/settings/logs/request`
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t("action"),
|
||||||
|
href: `/{orgId}/settings/logs/action`
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
400
src/app/[orgId]/settings/logs/request/page.tsx
Normal file
400
src/app/[orgId]/settings/logs/request/page.tsx
Normal file
@@ -0,0 +1,400 @@
|
|||||||
|
"use client";
|
||||||
|
import { Button } from "@app/components/ui/button";
|
||||||
|
import { toast } from "@app/hooks/useToast";
|
||||||
|
import { useState, useRef, useEffect } from "react";
|
||||||
|
import { createApiClient } from "@app/lib/api";
|
||||||
|
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||||
|
import { useParams, useRouter } from "next/navigation";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { LogDataTable } from "@app/components/LogDataTable";
|
||||||
|
import { ColumnDef } from "@tanstack/react-table";
|
||||||
|
import { DateTimeValue } from "@app/components/DateTimePicker";
|
||||||
|
import { Key, RouteOff, User, Lock, Unlock } from "lucide-react";
|
||||||
|
|
||||||
|
export default function GeneralPage() {
|
||||||
|
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||||
|
const router = useRouter();
|
||||||
|
const api = createApiClient(useEnvContext());
|
||||||
|
const t = useTranslations();
|
||||||
|
const { env } = useEnvContext();
|
||||||
|
const { orgId } = useParams();
|
||||||
|
|
||||||
|
const [rows, setRows] = useState<any[]>([]);
|
||||||
|
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||||
|
const [isExporting, setIsExporting] = useState(false);
|
||||||
|
|
||||||
|
// Pagination state
|
||||||
|
const [totalCount, setTotalCount] = useState<number>(0);
|
||||||
|
const [currentPage, setCurrentPage] = useState<number>(0);
|
||||||
|
const [pageSize, setPageSize] = useState<number>(20);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
|
// Set default date range to last 24 hours
|
||||||
|
const getDefaultDateRange = () => {
|
||||||
|
const now = new Date();
|
||||||
|
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||||
|
|
||||||
|
return {
|
||||||
|
startDate: {
|
||||||
|
date: yesterday
|
||||||
|
},
|
||||||
|
endDate: {
|
||||||
|
date: now
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const [dateRange, setDateRange] = useState<{
|
||||||
|
startDate: DateTimeValue;
|
||||||
|
endDate: DateTimeValue;
|
||||||
|
}>(getDefaultDateRange());
|
||||||
|
|
||||||
|
// Trigger search with default values on component mount
|
||||||
|
useEffect(() => {
|
||||||
|
const defaultRange = getDefaultDateRange();
|
||||||
|
queryDateTime(defaultRange.startDate, defaultRange.endDate);
|
||||||
|
}, [orgId]); // Re-run if orgId changes
|
||||||
|
|
||||||
|
const handleDateRangeChange = (
|
||||||
|
startDate: DateTimeValue,
|
||||||
|
endDate: DateTimeValue
|
||||||
|
) => {
|
||||||
|
setDateRange({ startDate, endDate });
|
||||||
|
setCurrentPage(0); // Reset to first page when filtering
|
||||||
|
queryDateTime(startDate, endDate, 0, pageSize);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle page changes
|
||||||
|
const handlePageChange = (newPage: number) => {
|
||||||
|
setCurrentPage(newPage);
|
||||||
|
queryDateTime(
|
||||||
|
dateRange.startDate,
|
||||||
|
dateRange.endDate,
|
||||||
|
newPage,
|
||||||
|
pageSize
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle page size changes
|
||||||
|
const handlePageSizeChange = (newPageSize: number) => {
|
||||||
|
setPageSize(newPageSize);
|
||||||
|
setCurrentPage(0); // Reset to first page when changing page size
|
||||||
|
queryDateTime(dateRange.startDate, dateRange.endDate, 0, newPageSize);
|
||||||
|
};
|
||||||
|
|
||||||
|
const queryDateTime = async (
|
||||||
|
startDate: DateTimeValue,
|
||||||
|
endDate: DateTimeValue,
|
||||||
|
page: number = currentPage,
|
||||||
|
size: number = pageSize
|
||||||
|
) => {
|
||||||
|
console.log("Date range changed:", { startDate, endDate, page, size });
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Convert the date/time values to API parameters
|
||||||
|
let params: any = {
|
||||||
|
limit: size,
|
||||||
|
offset: page * size
|
||||||
|
};
|
||||||
|
|
||||||
|
if (startDate?.date) {
|
||||||
|
const startDateTime = new Date(startDate.date);
|
||||||
|
if (startDate.time) {
|
||||||
|
const [hours, minutes, seconds] = startDate.time
|
||||||
|
.split(":")
|
||||||
|
.map(Number);
|
||||||
|
startDateTime.setHours(hours, minutes, seconds || 0);
|
||||||
|
}
|
||||||
|
params.timeStart = startDateTime.toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (endDate?.date) {
|
||||||
|
const endDateTime = new Date(endDate.date);
|
||||||
|
if (endDate.time) {
|
||||||
|
const [hours, minutes, seconds] = endDate.time
|
||||||
|
.split(":")
|
||||||
|
.map(Number);
|
||||||
|
endDateTime.setHours(hours, minutes, seconds || 0);
|
||||||
|
} else {
|
||||||
|
// If no time is specified, set to NOW
|
||||||
|
const now = new Date();
|
||||||
|
endDateTime.setHours(
|
||||||
|
now.getHours(),
|
||||||
|
now.getMinutes(),
|
||||||
|
now.getSeconds(),
|
||||||
|
now.getMilliseconds()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
params.timeEnd = endDateTime.toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await api.get(`/org/${orgId}/logs/request`, { params });
|
||||||
|
if (res.status === 200) {
|
||||||
|
setRows(res.data.data.log || []);
|
||||||
|
setTotalCount(res.data.data.pagination?.total || 0);
|
||||||
|
console.log("Fetched logs:", res.data);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
toast({
|
||||||
|
title: t("error"),
|
||||||
|
description: t("Failed to filter logs"),
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const refreshData = async () => {
|
||||||
|
console.log("Data refreshed");
|
||||||
|
setIsRefreshing(true);
|
||||||
|
try {
|
||||||
|
// Refresh data with current date range and pagination
|
||||||
|
await queryDateTime(
|
||||||
|
dateRange.startDate,
|
||||||
|
dateRange.endDate,
|
||||||
|
currentPage,
|
||||||
|
pageSize
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
toast({
|
||||||
|
title: t("error"),
|
||||||
|
description: t("refreshError"),
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsRefreshing(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const exportData = async () => {
|
||||||
|
try {
|
||||||
|
setIsExporting(true);
|
||||||
|
const response = await api.get(
|
||||||
|
`/org/${orgId}/logs/request/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",
|
||||||
|
`request-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"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 100 - Allowed by Rule
|
||||||
|
// 101 - Allowed No Auth
|
||||||
|
// 102 - Valid Access Token
|
||||||
|
// 103 - Valid header auth
|
||||||
|
// 104 - Valid Pincode
|
||||||
|
// 105 - Valid Password
|
||||||
|
// 106 - Valid email
|
||||||
|
// 107 - Valid SSO
|
||||||
|
|
||||||
|
// 201 - Resource Not Found
|
||||||
|
// 202 - Resource Blocked
|
||||||
|
// 203 - Dropped by Rule
|
||||||
|
// 204 - No Sessions
|
||||||
|
// 205 - Temporary Request Token
|
||||||
|
// 299 - No More Auth Methods
|
||||||
|
|
||||||
|
const reasonMap: any = {
|
||||||
|
100: t("allowedByRule"),
|
||||||
|
101: t("allowedNoAuth"),
|
||||||
|
102: t("validAccessToken"),
|
||||||
|
103: t("validHeaderAuth"),
|
||||||
|
104: t("validPincode"),
|
||||||
|
105: t("validPassword"),
|
||||||
|
106: t("validEmail"),
|
||||||
|
107: t("validSSO"),
|
||||||
|
201: t("resourceNotFound"),
|
||||||
|
202: t("resourceBlocked"),
|
||||||
|
203: t("droppedByRule"),
|
||||||
|
204: t("noSessions"),
|
||||||
|
205: t("temporaryRequestToken"),
|
||||||
|
299: t("noMoreAuthMethods")
|
||||||
|
};
|
||||||
|
|
||||||
|
// resourceId: integer("resourceId"),
|
||||||
|
// userAgent: text("userAgent"),
|
||||||
|
// metadata: text("details"),
|
||||||
|
// headers: text("headers"), // JSON blob
|
||||||
|
// query: text("query"), // JSON blob
|
||||||
|
// originalRequestURL: text("originalRequestURL"),
|
||||||
|
// scheme: text("scheme"),
|
||||||
|
|
||||||
|
const columns: ColumnDef<any>[] = [
|
||||||
|
{
|
||||||
|
accessorKey: "timestamp",
|
||||||
|
header: ({ column }) => {
|
||||||
|
return t("timestamp");
|
||||||
|
},
|
||||||
|
cell: ({ row }) => {
|
||||||
|
return (
|
||||||
|
<div className="whitespace-nowrap">
|
||||||
|
{new Date(
|
||||||
|
row.original.timestamp * 1000
|
||||||
|
).toLocaleString()}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
accessorKey: "ip",
|
||||||
|
header: ({ column }) => {
|
||||||
|
return t("ip");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
accessorKey: "location",
|
||||||
|
header: ({ column }) => {
|
||||||
|
return t("location");
|
||||||
|
},
|
||||||
|
cell: ({ row }) => {
|
||||||
|
return (
|
||||||
|
<span className="flex items-center gap-1">
|
||||||
|
{row.original.location ? (
|
||||||
|
<span className="text-muted-foreground text-xs">
|
||||||
|
({row.original.location})
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-muted-foreground text-xs">
|
||||||
|
-
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
accessorKey: "host",
|
||||||
|
header: ({ column }) => {
|
||||||
|
return t("host");
|
||||||
|
},
|
||||||
|
cell: ({ row }) => {
|
||||||
|
return (
|
||||||
|
<span className="flex items-center gap-1">
|
||||||
|
{row.original.tls ? (
|
||||||
|
<Lock className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<Unlock className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
{row.original.host}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "path",
|
||||||
|
header: ({ column }) => {
|
||||||
|
return t("path");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// {
|
||||||
|
// accessorKey: "scheme",
|
||||||
|
// header: ({ column }) => {
|
||||||
|
// return t("scheme");
|
||||||
|
// },
|
||||||
|
// },
|
||||||
|
{
|
||||||
|
accessorKey: "method",
|
||||||
|
header: ({ column }) => {
|
||||||
|
return t("method");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "reason",
|
||||||
|
header: ({ column }) => {
|
||||||
|
return t("reason");
|
||||||
|
},
|
||||||
|
cell: ({ row }) => {
|
||||||
|
return (
|
||||||
|
<span className="flex items-center gap-1">
|
||||||
|
{reasonMap[row.original.reason]}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "actor",
|
||||||
|
header: ({ column }) => {
|
||||||
|
return t("actor");
|
||||||
|
},
|
||||||
|
cell: ({ row }) => {
|
||||||
|
return (
|
||||||
|
<span className="flex items-center gap-1">
|
||||||
|
{row.original.actorType == "user" ? (
|
||||||
|
<User className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<Key className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
{row.original.actor}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<LogDataTable
|
||||||
|
columns={columns}
|
||||||
|
data={rows}
|
||||||
|
persistPageSize="request-logs-table"
|
||||||
|
title={t("requestLogs")}
|
||||||
|
searchPlaceholder={t("searchLogs")}
|
||||||
|
searchColumn="host"
|
||||||
|
onRefresh={refreshData}
|
||||||
|
isRefreshing={isRefreshing}
|
||||||
|
onExport={exportData}
|
||||||
|
isExporting={isExporting}
|
||||||
|
onDateRangeChange={handleDateRangeChange}
|
||||||
|
dateRange={{
|
||||||
|
start: dateRange.startDate,
|
||||||
|
end: dateRange.endDate
|
||||||
|
}}
|
||||||
|
defaultSort={{
|
||||||
|
id: "timestamp",
|
||||||
|
desc: false
|
||||||
|
}}
|
||||||
|
// Server-side pagination props
|
||||||
|
totalCount={totalCount}
|
||||||
|
currentPage={currentPage}
|
||||||
|
onPageChange={handlePageChange}
|
||||||
|
onPageSizeChange={handlePageSizeChange}
|
||||||
|
isLoading={isLoading}
|
||||||
|
defaultPageSize={pageSize}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -141,7 +141,7 @@ export const orgNavSections = (
|
|||||||
: []),
|
: []),
|
||||||
{
|
{
|
||||||
title: "sidebarLogs",
|
title: "sidebarLogs",
|
||||||
href: "/{orgId}/settings/logs/action",
|
href: "/{orgId}/settings/logs/request",
|
||||||
icon: <Logs className="h-4 w-4" />
|
icon: <Logs className="h-4 w-4" />
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -360,15 +360,36 @@ export function LogDataTable<TData, TValue>({
|
|||||||
data-state={
|
data-state={
|
||||||
row.getIsSelected() && "selected"
|
row.getIsSelected() && "selected"
|
||||||
}
|
}
|
||||||
|
className="text-xs" // made smaller
|
||||||
>
|
>
|
||||||
{row.getVisibleCells().map((cell) => (
|
{row.getVisibleCells().map((cell) => {
|
||||||
<TableCell key={cell.id}>
|
const originalRow =
|
||||||
{flexRender(
|
row.original as any;
|
||||||
cell.column.columnDef.cell,
|
const actionValue =
|
||||||
cell.getContext()
|
originalRow?.action;
|
||||||
)}
|
let className = "";
|
||||||
</TableCell>
|
|
||||||
))}
|
if (
|
||||||
|
typeof actionValue === "boolean"
|
||||||
|
) {
|
||||||
|
className = actionValue
|
||||||
|
? "bg-green-100 dark:bg-green-900"
|
||||||
|
: "bg-red-100 dark:bg-red-900";
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TableCell
|
||||||
|
key={cell.id}
|
||||||
|
className={`${className} py-2`} // made smaller
|
||||||
|
>
|
||||||
|
{flexRender(
|
||||||
|
cell.column.columnDef
|
||||||
|
.cell,
|
||||||
|
cell.getContext()
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))
|
))
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
Reference in New Issue
Block a user