1use std::collections::HashMap;
2
3use claw10_domain::{Permission, RoleId};
4
5pub struct RbacService {
6 role_permissions: HashMap<RoleId, Vec<Permission>>,
7}
8
9impl RbacService {
10 #[must_use]
11 pub fn new() -> Self {
12 Self {
13 role_permissions: HashMap::new(),
14 }
15 }
16
17 pub fn assign_permissions(&mut self, role_id: RoleId, permissions: Vec<Permission>) {
18 self.role_permissions.insert(role_id, permissions);
19 }
20
21 #[must_use]
22 pub fn get_role_permissions(&self, role_id: &RoleId) -> Vec<Permission> {
23 self.role_permissions
24 .get(role_id)
25 .cloned()
26 .unwrap_or_default()
27 }
28
29 #[must_use]
30 pub fn get_roles_permissions(&self, role_ids: &[RoleId]) -> Vec<Permission> {
31 let mut perms: Vec<Permission> = role_ids
32 .iter()
33 .flat_map(|rid| self.get_role_permissions(rid))
34 .collect();
35 perms.sort();
36 perms.dedup();
37 perms
38 }
39
40 #[must_use]
41 pub fn child_permissions(
42 parent_delegable: &[Permission],
43 requested: &[Permission],
44 ) -> Vec<Permission> {
45 let parent_set: std::collections::HashSet<&Permission> = parent_delegable.iter().collect();
46 requested
47 .iter()
48 .filter(|p| parent_set.contains(*p))
49 .cloned()
50 .collect()
51 }
52}
53
54impl Default for RbacService {
55 fn default() -> Self {
56 Self::new()
57 }
58}