use crate::ids::{Permission, RoleId};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Gate {
OwnerConsent,
Local(String),
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RoleSpec {
pub all: bool,
pub permissions: BTreeSet<Permission>,
pub may_invite_as: BTreeSet<RoleId>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RoleTable {
host: Option<RoleId>,
roles: BTreeMap<RoleId, RoleSpec>,
gates: BTreeMap<Permission, Gate>,
default_role: Option<RoleId>,
}
impl RoleTable {
pub fn new() -> Self {
Self::default()
}
pub fn role(mut self, id: &str, spec: RoleSpec) -> Self {
self.roles.insert(RoleId::new(id), spec);
self
}
pub fn with_host(mut self, id: &str) -> Self {
self.host = Some(RoleId::new(id));
self
}
pub fn with_default_role(mut self, id: &str) -> Self {
self.default_role = Some(RoleId::new(id));
self
}
pub fn gate(mut self, permission: &str, gate: Gate) -> Self {
self.gates.insert(Permission::new(permission), gate);
self
}
pub fn host_role(&self) -> Option<&RoleId> {
self.host.as_ref()
}
pub fn default_role(&self) -> Option<&RoleId> {
self.default_role.as_ref()
}
pub fn spec(&self, role: &RoleId) -> Option<&RoleSpec> {
self.roles.get(role)
}
pub fn knows(&self, role: &RoleId) -> bool {
self.roles.contains_key(role)
}
pub fn grants(&self, role: &RoleId, perm: &Permission) -> bool {
self.roles.get(role).is_some_and(|r| r.all || r.permissions.contains(perm))
}
pub fn gate_of(&self, perm: &Permission) -> Option<&Gate> {
self.gates.get(perm)
}
pub fn may_invite_as(&self, creator: &RoleId, target: &RoleId) -> bool {
self.roles.get(creator).is_some_and(|r| r.may_invite_as.contains(target))
}
pub fn role_ids(&self) -> impl Iterator<Item = &RoleId> {
self.roles.keys()
}
pub fn catalog(&self) -> BTreeSet<Permission> {
self.roles.values().flat_map(|r| r.permissions.iter().cloned()).chain(self.gates.keys().cloned()).collect()
}
}
impl RoleSpec {
pub fn with(perms: &[&str]) -> Self {
RoleSpec { all: false, permissions: perms.iter().map(|p| Permission::new(*p)).collect(), may_invite_as: BTreeSet::new() }
}
pub fn everything() -> Self {
RoleSpec { all: true, ..Default::default() }
}
pub fn inviting(mut self, roles: &[&str]) -> Self {
self.may_invite_as = roles.iter().map(|r| RoleId::new(*r)).collect();
self
}
}