#[cfg(feature = "permission")]
mod on {
use std::sync::Arc;
use laravel::auth::Authenticatable;
use laravel::routing::Route;
use saola_permission::{
Operation, PermissionRequirement, PermissionSubject, RequirePermission, ScopeFrame, resolve_scope,
};
use crate::context::ContextRegistry;
type Enforcer = Arc<dyn Fn(&mut Route, Vec<PermissionRequirement>) + Send + Sync>;
#[derive(Clone, Default)]
pub struct PermScope {
pub(crate) frames: Vec<ScopeFrame>,
enforcer: Option<Enforcer>,
}
impl PermScope {
pub fn with_frame(&self, frame: ScopeFrame) -> Self {
let mut next = self.clone();
next.frames.push(frame);
next
}
pub fn enforce_with<U: Authenticatable + PermissionSubject>(&mut self) {
self.enforcer = Some(Arc::new(|route, requirements| {
route.middleware(RequirePermission::<U>::new(requirements));
}));
}
pub fn module(&self, slug: &str) -> Self {
self.module_with(slug, &[])
}
pub fn module_with(&self, slug: &str, permissions: &[Operation]) -> Self {
self.with_frame(ScopeFrame::Module { slug: slug.to_owned(), permissions: permissions.to_vec() })
}
pub fn group(&self, permissions: &[Operation]) -> Self {
self.with_frame(ScopeFrame::Group { permissions: permissions.to_vec() })
}
}
pub struct RoutePerm {
scope: PermScope,
context: String,
methods: Vec<String>,
declared: Vec<Operation>,
}
impl RoutePerm {
pub fn new(scope: &PermScope, context: &str, methods: Vec<String>, route: &mut Route) -> Self {
let this = Self { scope: scope.clone(), context: context.to_owned(), methods, declared: Vec::new() };
this.enforce(route);
this
}
fn enforce(&self, route: &mut Route) {
let Some(enforcer) = &self.scope.enforcer else { return };
let (_, _, required) = resolve_scope(&self.context, &self.scope.frames, &self.declared);
if !required.is_empty() {
enforcer(route, required);
}
}
pub fn add(&mut self, route: &mut Route, ops: &[Operation]) {
self.declared.extend_from_slice(ops);
self.enforce(route);
}
pub fn record(&self, registry: &mut ContextRegistry, full_name: &str) {
let methods: Vec<&str> = self.methods.iter().map(String::as_str).collect();
registry.permissions_mut().declare_route(
&self.context,
&self.scope.frames,
Some(full_name),
&methods,
&self.declared,
);
}
}
}
#[cfg(not(feature = "permission"))]
mod off {
use laravel::routing::Route;
use crate::context::ContextRegistry;
#[derive(Clone, Default)]
pub struct PermScope;
impl PermScope {
pub fn module(&self, _slug: &str) -> Self {
Self
}
}
pub struct RoutePerm;
impl RoutePerm {
pub fn new(_: &PermScope, _: &str, _: Vec<String>, _: &mut Route) -> Self {
Self
}
pub fn record(&self, _: &mut ContextRegistry, _: &str) {}
}
}
#[cfg(feature = "permission")]
pub use on::{PermScope, RoutePerm};
#[cfg(not(feature = "permission"))]
pub use off::{PermScope, RoutePerm};