spawn_access_control/
access_manager.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use crate::{Role, Resource, AccessControl};
use std::collections::HashMap;
use tokio::sync::RwLock;
use std::sync::Arc;

pub struct AccessManager {
    users: RwLock<HashMap<String, AccessControl>>,
    rate_limiter: Arc<RwLock<RateLimiter>>,
}

#[derive(Clone)]
pub struct RateLimiter {
    #[allow(dead_code)]
    max_requests: u32,
    #[allow(dead_code)]
    window_size: chrono::Duration,
}

impl RateLimiter {
    pub fn new(max_requests: u32, window_size: chrono::Duration) -> Self {
        Self {
            max_requests,
            window_size,
        }
    }

    pub fn is_within_limit(&self) -> bool {
        true
    }
}

impl AccessManager {
    pub fn new() -> Self {
        Self {
            users: RwLock::new(HashMap::new()),
            rate_limiter: Arc::new(RwLock::new(RateLimiter::new(100, chrono::Duration::seconds(60)))),
        }
    }

    pub async fn add_user(&self, username: String, role: Role) {
        let mut users = self.users.write().await;
        let mut access_control = AccessControl::new();
        access_control.add_role(role);
        users.insert(username, access_control);
    }

    pub async fn check_access(&self, username: &str, resource: &Resource) -> bool {
        let users = self.users.read().await;
        if let Some(access_control) = users.get(username) {
            let rate_limiter = self.rate_limiter.read().await;
            if rate_limiter.is_within_limit() {
                return access_control.has_access(resource);
            }
        }
        false
    }

    pub async fn add_role_to_user(&self, username: &str, role: Role) {
        let mut users = self.users.write().await;
        if let Some(access_control) = users.get_mut(username) {
            access_control.add_role(role);
        }
    }
}