Crate rust_rbac

Source
Expand description

A flexible Role-Based Access Control (RBAC) system for Rust applications.

This crate provides a trait-based approach to implementing RBAC in Rust applications, with support for various storage backends and web frameworks.

§Features

  • Role-based permissions
  • Direct permissions to users
  • Multiple roles per user
  • Multiple permissions per role
  • Permission inheritance through roles
  • Flexible storage backends

§Example

use rust_rbac::{RbacService, MemoryStorage, Permission, Role};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a new RBAC service with in-memory storage
    let storage = MemoryStorage::new();
    let rbac = RbacService::new(storage);

    // Create permissions
    let create_post = Permission::new("create-post");
    let edit_post = Permission::new("edit-post");
    let delete_post = Permission::new("delete-post");

    rbac.create_permission(&create_post).await?;
    rbac.create_permission(&edit_post).await?;
    rbac.create_permission(&delete_post).await?;

    // Create roles
    let author = Role::new("author");
    let editor = Role::new("editor");
    let admin = Role::new("admin");

    rbac.create_role(&author).await?;
    rbac.create_role(&editor).await?;
    rbac.create_role(&admin).await?;

    // Assign permissions to roles
    rbac.assign_permission_to_role("create-post", "author").await?;
    rbac.assign_permission_to_role("edit-post", "editor").await?;
    rbac.assign_permission_to_role("delete-post", "admin").await?;

    // Assign roles to users
    let user_id = "user123";
    rbac.assign_role_to_subject("author", user_id).await?;

    // Check permissions
    assert!(rbac.subject_has_permission(user_id, "create-post").await?);
    assert!(!rbac.subject_has_permission(user_id, "delete-post").await?);

    Ok(())
}

Re-exports§

pub use models::permission::Permission;
pub use models::role::Role;
pub use models::subject::RbacSubject;
pub use storage::traits::RbacStorage;
pub use storage::memory::MemoryStorage;

Modules§

cache
Cache implementations for RBAC
error
middleware
Middleware implementations for web frameworks
models
storage

Structs§

RbacService
Main RBAC service that coordinates permission checking