rustysan-sword 0.1.1

Blade-inspired HTML templates for Rust
Documentation
//! Authentication and authorization results for `@auth`, `@guest` and the `@can` family.
use serde::Serialize;
use std::{collections::BTreeMap, fmt::Display};

/// What a view may know about the current user: whether they are logged in, and the outcome
/// of the authorization checks the template asks about.
///
/// Sword runs no policies. The handler makes its decisions with the application's own typed
/// authorization, which is asynchronous and cannot run inside a template, and records the
/// answers here. Pass the value as the view data `auth`:
///
/// ```
/// use rustysan_sword::AuthContext;
///
/// let auth = AuthContext::authenticated()
///     .guard("admin", false)
///     .ability("create-post", true)
///     .ability_for("update-post", 7, true)
///     .ability_for("update-post", 8, false);
/// let data = serde_json::json!({ "auth": auth });
/// # let _ = data;
/// ```
///
/// A check the template makes that was not recorded is a render error. It is never treated
/// as allowed or denied, so a forgotten ability cannot silently open or close a section.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct AuthContext {
    authenticated: bool,
    guards: BTreeMap<String, bool>,
    abilities: BTreeMap<String, bool>,
    subjects: BTreeMap<String, BTreeMap<String, bool>>,
}

impl AuthContext {
    /// A visitor who is not logged in.
    pub fn guest() -> Self {
        Self::default()
    }

    /// A logged-in user on the default guard.
    pub fn authenticated() -> Self {
        Self {
            authenticated: true,
            ..Self::default()
        }
    }

    /// Record whether the user is authenticated on a named guard, for `@auth('admin')`.
    pub fn guard(mut self, name: impl Into<String>, authenticated: bool) -> Self {
        self.guards.insert(name.into(), authenticated);
        self
    }

    /// Record the outcome of an ability that takes no subject, for `@can('create-post')`.
    pub fn ability(mut self, name: impl Into<String>, allowed: bool) -> Self {
        self.abilities.insert(name.into(), allowed);
        self
    }

    /// Record the outcome of an ability on one subject, for `@can('update-post', post.id)`.
    /// The subject is the string or integer the template passes, usually a record id.
    pub fn ability_for(
        mut self,
        name: impl Into<String>,
        subject: impl Display,
        allowed: bool,
    ) -> Self {
        self.subjects
            .entry(name.into())
            .or_default()
            .insert(subject.to_string(), allowed);
        self
    }
}