use std::collections::{HashMap, HashSet};
use crate::channel::{ConversationKind, InboundMessage};
pub const DEFAULT_REFUSAL: &str = "Sorry, I can only respond to people I have been set up for.";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SenderRole {
Owner,
Allowed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Admission {
Accept(SenderRole),
Ignore,
Refuse,
}
#[derive(Debug, Clone)]
pub struct AccessPolicy {
owners: HashMap<String, HashSet<String>>,
allowed: HashMap<String, HashSet<String>>,
refusal: Option<String>,
require_addressed_in_groups: bool,
approvals_require_owner: bool,
}
impl Default for AccessPolicy {
fn default() -> Self {
Self {
owners: HashMap::new(),
allowed: HashMap::new(),
refusal: Some(DEFAULT_REFUSAL.to_string()),
require_addressed_in_groups: true,
approvals_require_owner: false,
}
}
}
impl AccessPolicy {
pub fn new() -> Self {
Self::default()
}
pub fn owner(mut self, channel: impl Into<String>, user_id: impl Into<String>) -> Self {
self.owners
.entry(channel.into())
.or_default()
.insert(user_id.into());
self
}
pub fn allow(mut self, channel: impl Into<String>, user_id: impl Into<String>) -> Self {
self.allowed
.entry(channel.into())
.or_default()
.insert(user_id.into());
self
}
pub fn require_addressed_in_groups(mut self, required: bool) -> Self {
self.require_addressed_in_groups = required;
self
}
pub fn approvals_require_owner(mut self, required: bool) -> Self {
self.approvals_require_owner = required;
self
}
pub fn refusal(&self) -> Option<&str> {
self.refusal.as_deref()
}
pub fn role(&self, channel: &str, user_id: &str) -> Option<SenderRole> {
let has = |map: &HashMap<String, HashSet<String>>| {
map.get(channel).is_some_and(|ids| ids.contains(user_id))
};
if has(&self.owners) {
Some(SenderRole::Owner)
} else if has(&self.allowed) {
Some(SenderRole::Allowed)
} else {
None
}
}
pub fn may_approve(&self, channel: &str, user_id: &str) -> bool {
match self.role(channel, user_id) {
Some(SenderRole::Owner) => true,
Some(SenderRole::Allowed) => !self.approvals_require_owner,
None => false,
}
}
pub fn admit(&self, channel: &str, message: &InboundMessage) -> Admission {
if message.sender.is_bot {
return Admission::Ignore;
}
let grouped = message.conversation.kind != ConversationKind::Direct;
if grouped && self.require_addressed_in_groups && !message.addressed {
return Admission::Ignore;
}
match self.role(channel, &message.sender.id) {
Some(role) => Admission::Accept(role),
None => Admission::Refuse,
}
}
}