use std::borrow::Cow;
use std::sync::Arc;
use crate::column::Filter;
use crate::error::Result;
use crate::model::{Model, ModelMeta};
use crate::query::Builder;
use crate::relations::eager::Constraint;
use crate::relations::path::{ParsedPath, RelationPath};
pub trait AccessFilter: Send + Sync + 'static {
fn filter(&self, action: &str, model: &'static ModelMeta) -> Result<Option<Filter>>;
}
impl<F> AccessFilter for F
where
F: Fn(&str, &'static ModelMeta) -> Result<Option<Filter>> + Send + Sync + 'static,
{
fn filter(&self, action: &str, model: &'static ModelMeta) -> Result<Option<Filter>> {
self(action, model)
}
}
impl<A: AccessFilter + ?Sized> AccessFilter for Arc<A> {
fn filter(&self, action: &str, model: &'static ModelMeta) -> Result<Option<Filter>> {
(**self).filter(action, model)
}
}
#[derive(Clone)]
pub(crate) struct AccessConstraint {
pub(crate) filter: Arc<dyn AccessFilter>,
pub(crate) action: Cow<'static, str>,
}
impl AccessConstraint {
pub(crate) fn apply<R: Model>(&self, query: Builder<R>) -> Result<Builder<R>> {
Ok(match self.filter.filter(&self.action, R::meta())? {
Some(condition) => query.where_(condition),
None => query,
})
}
}
impl<M: Model> Builder<M> {
pub fn with_accessible<A: AccessFilter + Clone>(
self,
path: impl RelationPath<M>,
access: &A,
) -> Self {
self.with_accessible_for(path, "read", access)
}
pub fn with_accessible_for<A: AccessFilter + Clone>(
mut self,
path: impl RelationPath<M>,
action: impl Into<Cow<'static, str>>,
access: &A,
) -> Self {
let text = path.relation_path().into_owned();
let parsed = match ParsedPath::parse(&text) {
Ok(parsed) => parsed,
Err(error) => return self.with_error(error.to_string()),
};
let constraint = AccessConstraint {
filter: Arc::new(access.clone()),
action: action.into(),
};
for depth in 1..=parsed.segments.len() {
let node = self.eager.tree.entry(&parsed.segments[..depth]);
if depth == parsed.segments.len() && parsed.columns.is_some() {
node.columns.clone_from(&parsed.columns);
}
node.constraints
.push(Constraint::new_access(constraint.clone()));
}
self
}
}