use std::collections::{BTreeMap, BTreeSet};
use fastauth_core::plugin_prelude::*;
pub const STATEMENTS: &[(&str, &[&str])] = &[
(
"user",
&[
"create",
"list",
"set-role",
"ban",
"impersonate",
"impersonate-admins",
"delete",
"set-password",
"set-email",
"get",
"update",
],
),
("session", &["list", "revoke", "delete"]),
];
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Permissions(BTreeMap<String, BTreeSet<String>>);
impl Permissions {
pub fn new() -> Self {
Self::default()
}
pub fn allow(
mut self,
resource: impl Into<String>,
actions: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
self.0
.entry(resource.into())
.or_default()
.extend(actions.into_iter().map(Into::into));
self
}
pub fn admin() -> Self {
STATEMENTS
.iter()
.fold(Self::new(), |permissions, (resource, actions)| {
permissions.allow(
*resource,
actions
.iter()
.copied()
.filter(|action| *action != "impersonate-admins"),
)
})
}
pub fn authorize(&self, request: &Permissions) -> bool {
!request.0.is_empty()
&& request.0.iter().all(|(resource, actions)| {
!actions.is_empty()
&& self
.0
.get(resource)
.is_some_and(|granted| actions.is_subset(granted))
})
}
}