MeiliSearch/meilisearch-http/src/extractors/authentication/mod.rs

183 lines
4.9 KiB
Rust
Raw Normal View History

mod error;
2021-06-24 14:22:12 +02:00
use std::any::{Any, TypeId};
use std::collections::HashMap;
2021-06-23 18:54:33 +02:00
use std::marker::PhantomData;
use std::ops::Deref;
use actix_web::FromRequest;
use futures::future::err;
2021-06-24 14:22:12 +02:00
use futures::future::{ok, Ready};
2021-06-23 18:54:33 +02:00
use crate::error::ResponseError;
use error::AuthenticationError;
2021-06-23 18:54:33 +02:00
2021-06-23 19:35:26 +02:00
macro_rules! create_policies {
($($name:ident), *) => {
2021-06-24 14:22:12 +02:00
pub mod policies {
use std::collections::HashSet;
use crate::extractors::authentication::Policy;
$(
2021-06-24 16:27:13 +02:00
#[derive(Debug, Default)]
2021-06-24 14:22:12 +02:00
pub struct $name {
inner: HashSet<Vec<u8>>
2021-06-23 19:35:26 +02:00
}
2021-06-24 14:22:12 +02:00
impl $name {
pub fn new() -> Self {
Self { inner: HashSet::new() }
}
pub fn add(&mut self, token: Vec<u8>) {
2021-06-28 13:35:25 +02:00
self.inner.insert(token);
2021-06-24 14:22:12 +02:00
}
2021-06-23 19:35:26 +02:00
}
2021-06-24 14:22:12 +02:00
impl Policy for $name {
fn authenticate(&self, token: &[u8]) -> bool {
self.inner.contains(token)
}
2021-06-23 19:35:26 +02:00
}
2021-06-24 14:22:12 +02:00
)*
}
2021-06-23 19:35:26 +02:00
};
}
create_policies!(Public, Private, Admin);
/// Instanciate a `Policies`, filled with the given policies.
macro_rules! init_policies {
($($name:ident), *) => {
{
2021-06-24 14:22:12 +02:00
let mut policies = crate::extractors::authentication::Policies::new();
2021-06-23 19:35:26 +02:00
$(
let policy = $name::new();
policies.insert(policy);
)*
policies
}
};
}
/// Adds user to all specified policies.
macro_rules! create_users {
2021-06-24 14:22:12 +02:00
($policies:ident, $($user:expr => { $($policy:ty), * }), *) => {
2021-06-23 19:35:26 +02:00
{
$(
$(
2021-06-24 14:22:12 +02:00
$policies.get_mut::<$policy>().map(|p| p.add($user.to_owned()));
2021-06-23 19:35:26 +02:00
)*
)*
}
};
2021-06-23 18:54:33 +02:00
}
pub struct GuardedData<T, D> {
data: D,
_marker: PhantomData<T>,
}
impl<T, D> Deref for GuardedData<T, D> {
type Target = D;
fn deref(&self) -> &Self::Target {
&self.data
}
}
pub trait Policy {
fn authenticate(&self, token: &[u8]) -> bool;
}
2021-06-24 14:22:12 +02:00
#[derive(Debug)]
2021-06-23 18:54:33 +02:00
pub struct Policies {
inner: HashMap<TypeId, Box<dyn Any>>,
}
impl Policies {
pub fn new() -> Self {
2021-06-24 14:22:12 +02:00
Self {
inner: HashMap::new(),
}
2021-06-23 18:54:33 +02:00
}
pub fn insert<S: Policy + 'static>(&mut self, policy: S) {
self.inner.insert(TypeId::of::<S>(), Box::new(policy));
}
pub fn get<S: Policy + 'static>(&self) -> Option<&S> {
self.inner
.get(&TypeId::of::<S>())
.and_then(|p| p.downcast_ref::<S>())
2021-06-23 19:35:26 +02:00
}
pub fn get_mut<S: Policy + 'static>(&mut self) -> Option<&mut S> {
2021-06-24 14:22:12 +02:00
self.inner
.get_mut(&TypeId::of::<S>())
2021-06-23 19:35:26 +02:00
.and_then(|p| p.downcast_mut::<S>())
2021-06-23 18:54:33 +02:00
}
}
impl Default for Policies {
fn default() -> Self {
Self::new()
}
}
pub enum AuthConfig {
NoAuth,
Auth(Policies),
}
impl Default for AuthConfig {
fn default() -> Self {
Self::NoAuth
}
}
impl<P: Policy + 'static, D: 'static + Clone> FromRequest for GuardedData<P, D> {
type Config = AuthConfig;
type Error = ResponseError;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(
req: &actix_web::HttpRequest,
2021-09-08 12:34:56 +02:00
_payload: &mut actix_web::dev::Payload,
2021-06-23 18:54:33 +02:00
) -> Self::Future {
match req.app_data::<Self::Config>() {
Some(config) => match config {
AuthConfig::NoAuth => match req.app_data::<D>().cloned() {
Some(data) => ok(Self {
data,
_marker: PhantomData,
}),
None => err(AuthenticationError::IrretrievableState.into()),
2021-06-23 18:54:33 +02:00
},
AuthConfig::Auth(policies) => match policies.get::<P>() {
Some(policy) => match req.headers().get("x-meili-api-key") {
Some(token) => {
if policy.authenticate(token.as_bytes()) {
match req.app_data::<D>().cloned() {
Some(data) => ok(Self {
data,
_marker: PhantomData,
}),
None => err(AuthenticationError::IrretrievableState.into()),
2021-06-23 18:54:33 +02:00
}
} else {
err(AuthenticationError::InvalidToken(String::from("hello")).into())
}
}
None => err(AuthenticationError::MissingAuthorizationHeader.into()),
},
None => err(AuthenticationError::UnknownPolicy.into()),
2021-06-23 18:54:33 +02:00
},
},
None => err(AuthenticationError::IrretrievableState.into()),
2021-06-23 18:54:33 +02:00
}
}
}