Skip to content

Policies

The #[policy] attribute macro generates a Policy trait implementation for authorization logic.

Usage

rust
use larastvel_core::auth::{AuthenticatedUser, GateCheck};

#[policy("post")]
#[derive(Debug)]
struct PostPolicy;

impl PostPolicy {
    fn check_ability(&self, user: &AuthenticatedUser, ability: &str, args: &[String]) -> Option<GateCheck> {
        match ability {
            "view" | "create" | "update" => Some(GateCheck::Allowed),
            "delete" => Some(GateCheck::Denied("Admins only".to_string())),
            _ => None,
        }
    }
}

Arguments

ArgumentTypeRequiredDescription
resourcestring literalyesResource name (e.g. "post", "user")

Generated Implementation

The macro generates:

rust
impl PostPolicy {
    /// Register this policy with the given gate.
    pub fn register(gate: &larastvel_core::auth::Gate) {
        gate.register_policy("post", std::sync::Arc::new(PostPolicy));
    }
}

impl larastvel_core::auth::Policy for PostPolicy {
    fn resource(&self) -> &str {
        "post"
    }

    fn check(
        &self,
        user: &AuthenticatedUser,
        ability: &str,
        args: &[String],
    ) -> Option<GateCheck> {
        self.check_ability(user, ability, args)
    }
}

User Method

Your struct must define a check_ability method (name chosen to avoid collision with Policy::check):

rust
fn check_ability(&self, user: &AuthenticatedUser, ability: &str, args: &[String]) -> Option<GateCheck>

Registration

rust
PostPolicy::register(&gate);

CLI Generator

bash
larastvel make policy PostPolicy

Released under the MIT License.