policies macros

This commit is contained in:
marin postma 2021-06-23 19:35:26 +02:00
parent 12f6709e1c
commit 5b71751391
No known key found for this signature in database
GPG Key ID: 6088B7721C3E39F9
4 changed files with 64 additions and 7 deletions

View File

@ -1,4 +1,4 @@
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::marker::PhantomData;
use std::ops::Deref;
use std::any::{Any, TypeId};
@ -9,12 +9,59 @@ use futures::future::{Ready, ok};
use crate::error::{AuthenticationError, ResponseError};
pub struct Public;
macro_rules! create_policies {
($($name:ident), *) => {
$(
pub struct $name {
inner: HashSet<Vec<u8>>
}
impl Policy for Public {
fn authenticate(&self, _token: &[u8]) -> bool {
true
}
impl $name {
pub fn new() -> Self {
Self { inner: HashSet::new() }
}
pub fn add(&mut self, token: Vec<u8>) {
self.inner.insert(token);
}
}
impl Policy for $name {
fn authenticate(&self, token: &[u8]) -> bool {
self.inner.contains(token)
}
}
)*
};
}
create_policies!(Public, Private, Admin);
/// Instanciate a `Policies`, filled with the given policies.
macro_rules! init_policies {
($($name:ident), *) => {
{
let mut policies = Policies::new();
$(
let policy = $name::new();
policies.insert(policy);
)*
policies
}
};
}
/// Adds user to all specified policies.
macro_rules! create_users {
($policies:ident, $($user:literal => { $($policy:ty), * }), *) => {
{
$(
$(
$policies.get_mut::<$policy>().map(|p| p.add($user.to_owned()))
)*
)*
}
};
}
pub struct GuardedData<T, D> {
@ -52,6 +99,11 @@ impl Policies {
.get(&TypeId::of::<S>())
.and_then(|p| p.downcast_ref::<S>())
}
pub fn get_mut<S: Policy + 'static>(&mut self) -> Option<&mut S> {
self.inner.get_mut(&TypeId::of::<S>())
.and_then(|p| p.downcast_mut::<S>())
}
}
impl Default for Policies {

View File

@ -1,2 +1,3 @@
pub mod payload;
#[macro_use]
pub mod authentication;

View File

@ -35,6 +35,10 @@ pub fn configure_data(config: &mut web::ServiceConfig, data: Data) {
);
}
pub fn configure_auth(config: &mut web::ServiceConfig, opt: &Options) {
todo!()
}
#[cfg(feature = "mini-dashboard")]
pub fn dashboard(config: &mut web::ServiceConfig, enable_frontend: bool) {
use actix_web_static_files::Resource;

View File

@ -13,7 +13,7 @@ use crate::extractors::authentication::{Policies, AuthConfig, Public, GuardedDat
pub fn services(cfg: &mut web::ServiceConfig) {
let mut policies = Policies::new();
policies.insert(Public);
policies.insert(Public::new());
cfg.service(
web::resource("/indexes/{index_uid}/search")
.app_data(AuthConfig::Auth(policies))