fabaccess-bffh/src/access.rs

67 lines
1.7 KiB
Rust
Raw Normal View History

2020-02-14 12:20:17 +01:00
//! Access control logic
//!
2020-02-17 15:07:55 +01:00
use slog::Logger;
2020-02-14 12:20:17 +01:00
use casbin::prelude::*;
2020-02-18 16:55:19 +01:00
use crate::config::Config;
2020-02-17 14:56:43 +01:00
use crate::auth::Authentication;
use crate::error::Result;
2020-02-17 03:44:02 +01:00
2020-02-18 16:55:19 +01:00
use std::rc::Rc;
use async_std::sync::{Arc, RwLock};
use std::ops::Deref;
pub struct PermissionsProvider {
log: Logger,
pdb: Enforcer,
}
impl PermissionsProvider {
pub fn new(log: Logger, pdb: Enforcer) -> Self {
Self { log, pdb }
}
pub fn enforce(&self, actor: &str, object: &str, action: &str) -> Result<bool> {
let b = self.pdb.enforce(vec![actor, object, action])?;
2020-02-19 14:50:23 +01:00
if b {
trace!(self.log, "Granted {} on {} for {}", action, object, actor);
} else {
trace!(self.log, "Denied {} on {} for {}", action, object, actor);
}
2020-02-18 16:55:19 +01:00
Ok(b)
}
}
2020-02-17 03:44:02 +01:00
#[derive(Clone)]
2020-02-17 14:56:43 +01:00
pub struct Permissions {
2020-02-18 16:55:19 +01:00
inner: Arc<RwLock<PermissionsProvider>>,
auth: Rc<Authentication>,
2020-02-17 14:56:43 +01:00
}
impl Permissions {
2020-02-18 16:55:19 +01:00
pub fn new(inner: Arc<RwLock<PermissionsProvider>>, auth: Rc<Authentication>) -> Self {
Self { inner, auth }
2020-02-17 14:56:43 +01:00
}
2020-02-18 16:55:19 +01:00
pub async fn enforce(&self, object: &str, action: &str) -> Result<bool> {
if let Some(actor) = self.auth.state.read().await.deref() {
self.inner.read().await.enforce(&actor, object, action)
2020-02-17 14:56:43 +01:00
} else {
2020-02-18 16:55:19 +01:00
Ok(false)
2020-02-17 14:56:43 +01:00
}
}
}
2020-02-17 03:44:02 +01:00
/// This line documents init
2020-02-18 16:55:19 +01:00
pub async fn init(log: Logger, config: &Config) -> std::result::Result<PermissionsProvider, Box<dyn std::error::Error>> {
2020-02-14 12:20:17 +01:00
let model = Model::from_file(config.access.model.clone()).await?;
let adapter = Box::new(FileAdapter::new(config.access.policy.clone()));
let e = Enforcer::new(model, adapter).await?;
2020-02-18 16:55:19 +01:00
return Ok(PermissionsProvider::new(log, e));
2020-02-14 12:20:17 +01:00
}