saola-kit 0.2.0

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
Documentation
//! Route-level permission declarations for [`ContextRoutes`](super::ContextRoutes).
//!
//! With the `permission` feature, modules and groups carry permission frames, every route records
//! its row into the registry's [`RoutePermissionRegistry`](saola_permission::RoutePermissionRegistry)
//! when it is named, and (after [`ContextRoutes::enforce_with`](super::ContextRoutes::enforce_with))
//! gets a `RequirePermission` middleware. Without the feature everything here is a no-op.

#[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>;

    /// Frames (context group, modules, groups) and the optional enforcer in effect for new routes.
    #[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() })
        }
    }

    /// Per-route state: what was declared on the route itself plus the scope it lives in.
    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);
            }
        }

        /// Adds operations declared on this route; the extra middleware stacks (AND) with the
        /// scope-level one added at registration.
        pub fn add(&mut self, route: &mut Route, ops: &[Operation]) {
            self.declared.extend_from_slice(ops);
            self.enforce(route);
        }

        /// Records the route's row into the registry. Call after `add`; routes without any
        /// requirement are skipped.
        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};