Skip to main content

saola_kit/envelope/
auth.rs

1use std::collections::BTreeMap;
2
3use serde::Serialize;
4use serde_json::Value;
5
6/// Projected authenticated user sent to the Saola client (`auth.guards.<name>.user`).
7/// Never serializes a whole database model; callers project only safe public fields.
8#[derive(Debug, Clone, PartialEq, Serialize)]
9pub struct ClientAuthUser {
10    pub id: Value,
11    #[serde(flatten)]
12    pub fields: BTreeMap<String, Value>,
13}
14
15impl ClientAuthUser {
16    pub fn new(id: impl Into<Value>) -> Self {
17        Self {
18            id: id.into(),
19            fields: BTreeMap::new(),
20        }
21    }
22
23    pub fn with_field(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
24        self.fields.insert(key.into(), value.into());
25        self
26    }
27}
28
29#[derive(Debug, Clone, PartialEq, Serialize)]
30pub struct ClientGuardState {
31    pub user: Option<ClientAuthUser>,
32}
33
34/// Request-scoped authentication projection matching `ClientAuth::export` (`version: 1`).
35#[derive(Debug, Clone, PartialEq, Serialize)]
36pub struct ClientAuthProjection {
37    pub version: u8,
38    #[serde(rename = "defaultGuard")]
39    pub default_guard: String,
40    pub guards: BTreeMap<String, ClientGuardState>,
41}
42
43impl ClientAuthProjection {
44    pub fn guest(default_guard: impl Into<String>) -> Self {
45        let guard = default_guard.into();
46        let mut guards = BTreeMap::new();
47        guards.insert(guard.clone(), ClientGuardState { user: None });
48        Self {
49            version: 1,
50            default_guard: guard,
51            guards,
52        }
53    }
54
55    pub fn authenticated(default_guard: impl Into<String>, user: ClientAuthUser) -> Self {
56        let guard = default_guard.into();
57        let mut guards = BTreeMap::new();
58        guards.insert(guard.clone(), ClientGuardState { user: Some(user) });
59        Self {
60            version: 1,
61            default_guard: guard,
62            guards,
63        }
64    }
65
66    pub fn with_guard(mut self, name: impl Into<String>, user: Option<ClientAuthUser>) -> Self {
67        self.guards.insert(name.into(), ClientGuardState { user });
68        self
69    }
70}