forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

audit.rs57 lines, 1.8 KiBHistoryRawDownload
1//! The audit writer of the web layer. Every change of an account, a session or a sign-in goes
2//! through [`record`].
3//!
4//! The entry is written after the change has committed. A failed write is logged and never fails
5//! the request: a person who has just signed in should not see an error because the log was busy.
6//! Nothing secret goes in `data`; callers pass counts, reasons and ids only.
7
8use im_core::model::AuditAction;
9use im_core::store::audit::NewAudit;
10use serde_json::Value;
11use topcoat::context::{Cx, app_context};
12
13use crate::client_ip::client_addr;
14use crate::state::AppState;
15
16/// Who performed the action.
17#[derive(Clone, Copy)]
18pub enum Actor<'a> {
19 /// A signed-in person, by their id.
20 User(&'a str),
21 /// Nobody is signed in: a failed sign-in, for example.
22 Anonymous,
23}
24
25/// Appends one entry. `target` is the kind and id of what the action was about; `data` is JSON
26/// (`Value::Null` for none).
27pub async fn record(
28 cx: &Cx,
29 actor: Actor<'_>,
30 action: AuditAction,
31 target: Option<(&str, &str)>,
32 data: Value,
33) {
34 let state = app_context::<AppState>(cx);
35 let ip = client_addr(cx).to_string();
36 let (actor_id, actor_kind) = match actor {
37 Actor::User(id) => (Some(id), "user"),
38 Actor::Anonymous => (None, "anonymous"),
39 };
40 let data_text = (!data.is_null()).then(|| data.to_string());
41 let entry = NewAudit {
42 actor_id,
43 actor_kind,
44 action: action.as_str(),
45 target_kind: target.map(|(kind, _)| kind),
46 target_id: target.map(|(_, id)| id),
47 ip: Some(ip.as_str()),
48 data: data_text.as_deref(),
49 };
50 if let Err(error) = state.store.record_audit(&entry).await {
51 tracing::error!(
52 error = %error,
53 action = action.as_str(),
54 "audit entry was not written"
55 );
56 }
57}