1use crate::ids::{Permission, RoleId};
3use serde::{Deserialize, Serialize};
4use std::collections::{BTreeMap, BTreeSet};
5
6#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
8pub enum Gate {
9 OwnerConsent,
12 Local(String),
15}
16
17#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
19pub struct RoleSpec {
20 pub all: bool,
22 pub permissions: BTreeSet<Permission>,
24 pub may_invite_as: BTreeSet<RoleId>,
26}
27
28#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
30pub struct RoleTable {
31 host: Option<RoleId>,
32 roles: BTreeMap<RoleId, RoleSpec>,
33 gates: BTreeMap<Permission, Gate>,
34 default_role: Option<RoleId>,
35}
36
37impl RoleTable {
38 pub fn new() -> Self {
40 Self::default()
41 }
42
43 pub fn role(mut self, id: &str, spec: RoleSpec) -> Self {
45 self.roles.insert(RoleId::new(id), spec);
46 self
47 }
48
49 pub fn with_host(mut self, id: &str) -> Self {
51 self.host = Some(RoleId::new(id));
52 self
53 }
54
55 pub fn with_default_role(mut self, id: &str) -> Self {
57 self.default_role = Some(RoleId::new(id));
58 self
59 }
60
61 pub fn gate(mut self, permission: &str, gate: Gate) -> Self {
63 self.gates.insert(Permission::new(permission), gate);
64 self
65 }
66
67 pub fn host_role(&self) -> Option<&RoleId> {
69 self.host.as_ref()
70 }
71
72 pub fn default_role(&self) -> Option<&RoleId> {
74 self.default_role.as_ref()
75 }
76
77 pub fn spec(&self, role: &RoleId) -> Option<&RoleSpec> {
79 self.roles.get(role)
80 }
81
82 pub fn knows(&self, role: &RoleId) -> bool {
84 self.roles.contains_key(role)
85 }
86
87 pub fn grants(&self, role: &RoleId, perm: &Permission) -> bool {
89 self.roles.get(role).is_some_and(|r| r.all || r.permissions.contains(perm))
90 }
91
92 pub fn gate_of(&self, perm: &Permission) -> Option<&Gate> {
94 self.gates.get(perm)
95 }
96
97 pub fn may_invite_as(&self, creator: &RoleId, target: &RoleId) -> bool {
99 self.roles.get(creator).is_some_and(|r| r.may_invite_as.contains(target))
100 }
101
102 pub fn role_ids(&self) -> impl Iterator<Item = &RoleId> {
104 self.roles.keys()
105 }
106
107 pub fn catalog(&self) -> BTreeSet<Permission> {
109 self.roles.values().flat_map(|r| r.permissions.iter().cloned()).chain(self.gates.keys().cloned()).collect()
110 }
111}
112
113impl RoleSpec {
114 pub fn with(perms: &[&str]) -> Self {
116 RoleSpec { all: false, permissions: perms.iter().map(|p| Permission::new(*p)).collect(), may_invite_as: BTreeSet::new() }
117 }
118
119 pub fn everything() -> Self {
121 RoleSpec { all: true, ..Default::default() }
122 }
123
124 pub fn inviting(mut self, roles: &[&str]) -> Self {
126 self.may_invite_as = roles.iter().map(|r| RoleId::new(*r)).collect();
127 self
128 }
129}