use rusqlite::params; use crate::db::{Db, Writer}; use crate::error::Result; use crate::time; pub fn audit( writer: &Writer, actor_kind: &str, actor: &str, action: &str, entity: &str, entity_id: &str, detail: serde_json::Value, ) -> Result<()> { let at = time::now(); let actor_kind = actor_kind.to_string(); let actor = actor.to_string(); let action = action.to_string(); let entity = entity.to_string(); let entity_id = entity_id.to_string(); writer.tx(move |tx| { audit_in( tx, &AuditEntry { at: &at, actor_kind: &actor_kind, actor: &actor, action: &action, entity: &entity, entity_id: &entity_id, detail, }, ) }) } #[derive(Debug)] pub struct AuditEntry<'a> { pub at: &'a str, pub actor_kind: &'a str, pub actor: &'a str, pub action: &'a str, pub entity: &'a str, pub entity_id: &'a str, pub detail: serde_json::Value, } impl<'a> AuditEntry<'a> { pub fn human( at: &'a str, actor: &'a str, action: &'a str, entity: &'a str, entity_id: &'a str, detail: serde_json::Value, ) -> Self { Self { at, actor_kind: "human", actor, action, entity, entity_id, detail } } } pub fn audit_in(tx: &rusqlite::Transaction<'_>, e: &AuditEntry<'_>) -> Result<()> { tx.execute( "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) VALUES (?1,?2,?3,?4,?5,?6,?7)", params![e.at, e.actor_kind, e.actor, e.action, e.entity, e.entity_id, e.detail.to_string()], )?; Ok(()) } pub fn audit_system( writer: &Writer, action: &str, entity: &str, entity_id: &str, detail: serde_json::Value, ) -> Result<()> { audit(writer, "system", "", action, entity, entity_id, detail) } #[derive(Debug, Clone)] pub struct AuditRow { pub id: i64, pub at: String, pub actor_kind: String, pub actor: String, pub action: String, pub entity: String, pub entity_id: String, pub detail_json: String, } pub fn list_audit(db: &Db, limit: i64) -> Result> { db.read(|c| { let mut stmt = c.prepare( "SELECT id, at, actor_kind, actor, action, entity, entity_id, detail_json FROM audit ORDER BY id DESC LIMIT ?1", )?; let rows = stmt.query_map(params![limit], |r| { Ok(AuditRow { id: r.get(0)?, at: r.get(1)?, actor_kind: r.get(2)?, actor: r.get(3)?, action: r.get(4)?, entity: r.get(5)?, entity_id: r.get(6)?, detail_json: r.get(7)?, }) })?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) }