rocket_casbin_auth

Crates.iorocket_casbin_auth
lib.rsrocket_casbin_auth
version0.1.1
sourcesrc
created_at2020-08-26 19:44:59.554639
updated_at2020-08-27 05:10:39.226119
descriptionCasbin Rocket access control middleware
homepagehttps://github.com/simoin/rocket-casbin-auth
repository
max_upload_size
id281077
size21,071
(oiatz)

documentation

https://docs.rs/rocket-casbin-auth

README

Rocket Casbin Middleware

Crates.io Docs

Usage

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.

pub struct CasbinFairing {
    enforcer: Arc<RwLock<CachedEnforcer>>,
}

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

impl CasbinMiddleware for CasbinFairing {
    fn get_casbin_vals<'a>(&self, req: &Request<'_>) -> Vec<String> {
        let path = req.uri().path().to_owned();
        let sub = match req.cookies().get("name") {
            Some(cookie) => cookie.value().to_owned(),
            _ => "".to_owned(),
        };
        let method = req.method().as_str().to_owned();
        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.

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

finish, add guard to your route

#[get("/book/1")]
pub fn book(_g: CasbinGuard) -> &'static str {
    "book"
}
Commit count: 0

cargo fmt