Crates.io | rocket_casbin_auth |
lib.rs | rocket_casbin_auth |
version | 0.1.1 |
source | src |
created_at | 2020-08-26 19:44:59.554639 |
updated_at | 2020-08-27 05:10:39.226119 |
description | Casbin Rocket access control middleware |
homepage | https://github.com/simoin/rocket-casbin-auth |
repository | |
max_upload_size | |
id | 281077 |
size | 21,071 |
rocket_casbin_auth = "0.1.1"
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"
}