1use std::collections::HashSet;
4
5#[derive(Debug, Clone, Default)]
8pub struct Access {
9 chats: HashSet<String>,
10 users: HashSet<String>,
11}
12
13impl Access {
14 pub fn new<C, U>(chats: C, users: U) -> Self
15 where
16 C: IntoIterator<Item = String>,
17 U: IntoIterator<Item = String>,
18 {
19 Self {
20 chats: chats.into_iter().filter(|s| !s.is_empty()).collect(),
21 users: users.into_iter().filter(|s| !s.is_empty()).collect(),
22 }
23 }
24
25 pub fn allows(&self, chat_id: &str, user_id: &str) -> bool {
26 !user_id.is_empty() && self.chats.contains(chat_id) && self.users.contains(user_id)
27 }
28
29 pub fn warn_if_closed(&self, channel: &str) {
31 if self.chats.is_empty() || self.users.is_empty() {
32 tracing::warn!(
33 channel,
34 "no chat or no allowed_user_ids configured, incoming messages are dropped"
35 );
36 }
37 }
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43
44 fn access(chats: &[&str], users: &[&str]) -> Access {
45 Access::new(
46 chats.iter().map(ToString::to_string),
47 users.iter().map(ToString::to_string),
48 )
49 }
50
51 #[test]
52 fn allows_listed_chat_and_user() {
53 assert!(access(&["1"], &["9"]).allows("1", "9"));
54 }
55
56 #[test]
57 fn rejects_other_chat_or_user() {
58 let a = access(&["1"], &["9"]);
59 assert!(!a.allows("2", "9"));
60 assert!(!a.allows("1", "8"));
61 assert!(!a.allows("1", ""));
62 }
63
64 #[test]
65 fn empty_policy_rejects_everything() {
66 assert!(!access(&[], &[]).allows("1", "9"));
67 assert!(!access(&["1"], &[]).allows("1", "9"));
68 assert!(!access(&[], &["9"]).allows("1", "9"));
69 }
70}