import { Hono } from "jsr:@hono/hono@4"; import { sqlWrapper } from "../../db.ts"; import { valkey } from "../../valkey.ts"; import { auditWrapper } from "../../audit.ts"; import { getAuthenticatedUser, isGlobalAdmin } from "../../auth-session.ts"; import { getClientIp } from "../../middleware.ts"; export const auditAdminRoutes = new Hono(); auditAdminRoutes.get("/audit-logs", async (c) => { const auth = await getAuthenticatedUser(c); if (!auth) return c.json({ error: "Unauthorized" }, 401); const logs = await sqlWrapper.sql` SELECT a.id, a.action, a.resource, a.details, a.ip_address, a.created_at, u.username as user FROM audit_records a LEFT JOIN users u ON a.user_id = u.id ORDER BY a.created_at DESC LIMIT 100 `; return c.json({ logs }); }); auditAdminRoutes.get("/check", async (c) => { const auth = await getAuthenticatedUser(c); if (!auth) return c.json({ error: "Unauthorized" }, 401); const isAdmin = await isGlobalAdmin(auth.userId); return c.json({ isAdmin }); }); auditAdminRoutes.delete("/sessions/:id", async (c) => { const auth = await getAuthenticatedUser(c); if (!auth) return c.json({ error: "Unauthorized" }, 401); const sessionId = c.req.param("id"); const session = await sqlWrapper .sql`DELETE FROM sessions WHERE id = ${sessionId} RETURNING user_id` .then((res: any) => res[0]); if (session) { try { await valkey.del(sessionId); } catch (_err) {} auditWrapper.auditLog( auth.userId, "admin_session_revoked", session.user_id, { revoked_session_id: sessionId, }, getClientIp(c), ); } return c.json({ success: true }); });