use serde::Serialize;
use std::{collections::BTreeMap, fmt::Display};
#[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 {
pub fn guest() -> Self {
Self::default()
}
pub fn authenticated() -> Self {
Self {
authenticated: true,
..Self::default()
}
}
pub fn guard(mut self, name: impl Into<String>, authenticated: bool) -> Self {
self.guards.insert(name.into(), authenticated);
self
}
pub fn ability(mut self, name: impl Into<String>, allowed: bool) -> Self {
self.abilities.insert(name.into(), allowed);
self
}
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
}
}