use forge_core::{AuditAction, AuditEntry, Store, User}; use serde_json::Value; use topcoat::context::Cx; use crate::client_ip::client_ip; use crate::live::Topic; pub enum Actor<'a> { User(&'a User), Anonymous, Cli, } #[derive(Default)] pub struct Target<'a> { pub kind: &'a str, pub id: &'a str, pub name: &'a str, } pub async fn record( store: &Store, cx: Option<&Cx>, actor: Actor<'_>, action: AuditAction, target: Target<'_>, data: Value, ) { let mut entry = AuditEntry::new(action); match actor { Actor::User(user) => { entry.actor_id = Some(user.id.clone()); entry.actor_name = user.username.clone(); } Actor::Anonymous => {} Actor::Cli => entry.actor_name = "cli".to_string(), } entry.target_kind = target.kind.to_string(); entry.target_id = target.id.to_string(); entry.target_name = target.name.to_string(); entry.ip = cx.map(|cx| client_ip(cx).to_string()).unwrap_or_default(); if !data.is_null() { entry.data = data.to_string(); } if let Err(err) = store.record_audit(&entry).await { tracing::error!(action = action.as_str(), error = %err, "failed to record audit entry"); return; } let hub = crate::live::admin(); hub.bump(&Topic::AdminAudit); hub.bump(&Topic::AdminUsers); if let Some(actor) = &entry.actor_id { hub.bump(&Topic::AdminUser(actor.clone())); } if target.kind == "user" && !target.id.is_empty() { hub.bump(&Topic::AdminUser(target.id.to_string())); } }