use crate::policy::{Action, PolicyRule, Resource};
use alloc::collections::BTreeMap;
use alloc::string::String;
#[derive(Debug)]
pub struct PolicyAuthorizer<'a> {
rules: &'a [PolicyRule],
}
impl<'a> PolicyAuthorizer<'a> {
#[must_use]
pub const fn new(rules: &'a [PolicyRule]) -> Self {
Self { rules }
}
#[must_use]
pub fn is_allowed(&self, peer_id: &str, action: &Action, resource: &Resource) -> bool {
self.rules
.iter()
.any(|rule| rule.allows(peer_id, action, resource))
}
#[must_use]
pub fn is_allowed_with_context(
&self,
peer_id: &str,
action: &Action,
resource: &Resource,
current_time: u64,
context: &BTreeMap<String, String>,
) -> bool {
self.rules
.iter()
.any(|rule| rule.allows_with_context(peer_id, action, resource, current_time, context))
}
pub fn matching_rules(
&'a self,
peer_id: &'a str,
action: &'a Action,
resource: &'a Resource,
) -> impl Iterator<Item = &'a PolicyRule> + 'a {
self.rules
.iter()
.filter(move |rule| rule.allows(peer_id, action, resource))
}
#[must_use]
pub fn rule_count(&self) -> usize {
self.rules.len()
}
}
pub trait Authorizer {
fn is_allowed(&self, peer_id: &str, action: &Action, resource: &Resource) -> bool;
}
impl<'a> Authorizer for PolicyAuthorizer<'a> {
fn is_allowed(&self, peer_id: &str, action: &Action, resource: &Resource) -> bool {
PolicyAuthorizer::is_allowed(self, peer_id, action, resource)
}
}