saola-kit 0.1.3

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
Documentation
use std::collections::BTreeMap;

use serde::Serialize;
use serde_json::Value;

/// Projected authenticated user sent to the Saola client (`auth.guards.<name>.user`).
/// Never serializes a whole database model; callers project only safe public fields.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ClientAuthUser {
    pub id: Value,
    #[serde(flatten)]
    pub fields: BTreeMap<String, Value>,
}

impl ClientAuthUser {
    pub fn new(id: impl Into<Value>) -> Self {
        Self {
            id: id.into(),
            fields: BTreeMap::new(),
        }
    }

    pub fn with_field(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.fields.insert(key.into(), value.into());
        self
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ClientGuardState {
    pub user: Option<ClientAuthUser>,
}

/// Request-scoped authentication projection matching `ClientAuth::export` (`version: 1`).
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ClientAuthProjection {
    pub version: u8,
    #[serde(rename = "defaultGuard")]
    pub default_guard: String,
    pub guards: BTreeMap<String, ClientGuardState>,
}

impl ClientAuthProjection {
    pub fn guest(default_guard: impl Into<String>) -> Self {
        let guard = default_guard.into();
        let mut guards = BTreeMap::new();
        guards.insert(guard.clone(), ClientGuardState { user: None });
        Self {
            version: 1,
            default_guard: guard,
            guards,
        }
    }

    pub fn authenticated(default_guard: impl Into<String>, user: ClientAuthUser) -> Self {
        let guard = default_guard.into();
        let mut guards = BTreeMap::new();
        guards.insert(guard.clone(), ClientGuardState { user: Some(user) });
        Self {
            version: 1,
            default_guard: guard,
            guards,
        }
    }

    pub fn with_guard(mut self, name: impl Into<String>, user: Option<ClientAuthUser>) -> Self {
        self.guards.insert(name.into(), ClientGuardState { user });
        self
    }
}