Rocket Casbin Middleware

Crates.io Docs

Usage

rust rocket_casbin_auth = "0.1.1"

Guide

According to Rocket Fairing Guide, we need to use Fairing trait for authentication or authorization with casbin.

So you need to implement CasbinMiddleware and Fairing first. ```rust pub struct CasbinFairing { enforcer: Arc>, }

impl CasbinFairing { pub fn new(m: M, a: A) -> CasbinFairing { let mut rt = tokio::runtime::Runtime::new().unwrap(); match rt.blockon(casbin::CachedEnforcer::new(m, a)) { Ok(e) => CasbinFairing { enforcer: Arc::new(RwLock::new(e)), }, Err() => panic!("CasbinFairing build failed"), } } }

impl CasbinMiddleware for CasbinFairing { fn getcasbinvals<'a>(&self, req: &Request<'>) -> Vec { let path = req.uri().path().toowned(); let sub = match req.cookies().get("name") { Some(cookie) => cookie.value().toowned(), _ => "".toowned(), }; let method = req.method().asstr().toowned(); vec![sub, path, method] }

fn get_cached_enforcer(&self) -> Arc<RwLock<CachedEnforcer>> {
    self.enforcer.clone()
}

}

impl Fairing for CasbinFairing { fn info(&self) -> Info { Info { name: "Casbin Fairing", kind: Kind::Request, } }

fn on_request(&self, req: &mut Request<'r>, _: &Data) {
    self.enforce(req);
}

} ```

and then, attach fairing to rocket.

rust rocket::ignite() .attach(CasbinFairing::new("examples/model.conf", "examples/role_policy.csv"))

finish, add guard to your route

```rust

[get("/book/1")]

pub fn book(_g: CasbinGuard) -> &'static str { "book" } ```