5 releases

0.73.3 Oct 31, 2024
0.73.2 Oct 15, 2024
0.73.1 Oct 15, 2024
0.73.0 Oct 15, 2024
0.2.0 Oct 15, 2024

#495 in Development tools

Download history 468/week @ 2024-10-14 126/week @ 2024-10-21 148/week @ 2024-10-28 23/week @ 2024-11-04 18/week @ 2024-11-11

328 downloads per month
Used in 2 crates (via dipper)

Apache-2.0

9KB
98 lines

salvo-casbin

Crates.io Docs CI Codecov

Casbin access control hoop for salvo framework

Install

Add dependencies to Cargo.toml

cargo add salvo
cargo add salvo-casbin
cargo add tokio --features full

Requirement

Casbin only takes charge of permission control, so you need to implement an Authentication Middleware to identify user.

For example:

use casbin::function_map::key_match2;
use casbin::{CoreApi, DefaultModel, Enforcer, FileAdapter};
use salvo::prelude::*;
use salvo_casbin::{CasbinHoop, CasbinVals};

// Handler that immediately returns an empty `200 OK` response.
#[handler]
async fn handler() {}

#[tokio::main]
async fn main() {
    let m = DefaultModel::from_file("examples/rbac_with_pattern_model.conf")
        .await
        .unwrap();

    let a = FileAdapter::new("examples/rbac_with_pattern_policy.csv");

    let casbin_hoop = CasbinHoop::new(Enforcer::new(m, a).await.unwrap(), false, |_req, _depot| {
        Ok(Some(CasbinVals {
            subject: String::from("alice"),
            domain: None,
        }))
    });

    casbin_hoop
        .write()
        .await
        .get_role_manager()
        .write()
        .matching_fn(Some(key_match2), None);

    let app = Router::new()
        .hoop(casbin_hoop)
        .push(Router::with_path("/pen/1").get(handler))
        .push(Router::with_path("/pen/2").get(handler))
        .push(Router::with_path("/book/<id>").get(handler));
    
    let acceptor = TcpListener::new("127.0.0.1:5800").bind().await;
    Server::new(acceptor).serve(app).await;
}

License

This project is licensed under

Dependencies

~24–37MB
~659K SLoC