Skip to main content

linkrs_server/client/
role_context.rs

1use linkrs_core::RoleType;
2use parking_lot::RwLock;
3use std::collections::HashMap;
4use std::sync::Arc;
5
6#[derive(Debug)]
7pub struct RoleContext {
8    roles: Arc<RwLock<HashMap<i64, RoleType>>>,
9}
10
11impl Default for RoleContext {
12    fn default() -> Self {
13        Self::new()
14    }
15}
16
17impl RoleContext {
18    pub fn new() -> Self {
19        Self {
20            roles: Arc::new(RwLock::new(HashMap::new())),
21        }
22    }
23
24    pub fn roles(&self) -> HashMap<i64, RoleType> {
25        self.roles.read().clone()
26    }
27
28    pub fn role_with_space(&self, space: i64) -> Option<RoleType> {
29        self.roles.read().get(&space).cloned()
30    }
31
32    pub fn set_role(&self, space: i64, role: RoleType) {
33        self.roles.write().insert(space, role);
34    }
35
36    pub fn is_god(&self) -> bool {
37        self.roles
38            .read()
39            .values()
40            .any(|role| *role == RoleType::God)
41    }
42
43    pub fn is_admin(&self) -> bool {
44        self.roles
45            .read()
46            .values()
47            .any(|role| *role == RoleType::Admin || *role == RoleType::God)
48    }
49
50    pub fn is_schema_admin(&self) -> bool {
51        self.roles
52            .read()
53            .values()
54            .any(|role| matches!(*role, RoleType::God | RoleType::Admin | RoleType::Dba))
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn test_role_context() {
64        let context = RoleContext::new();
65        assert!(context.role_with_space(1).is_none());
66        assert!(!context.is_admin());
67        assert!(!context.is_god());
68
69        context.set_role(1, RoleType::Admin);
70        assert_eq!(context.role_with_space(1), Some(RoleType::Admin));
71        assert!(context.is_admin());
72        assert!(!context.is_god());
73
74        context.set_role(2, RoleType::God);
75        assert!(context.is_god());
76    }
77}