api: inline the ListUsersRequest

This commit is contained in:
Valentin Tolmer 2021-08-30 10:18:59 +02:00 committed by nitnelave
parent 08a3845cbe
commit cd91b4d3ac
6 changed files with 54 additions and 75 deletions

View File

@ -67,19 +67,6 @@ pub mod registration {
} }
} }
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
pub enum RequestFilter {
And(Vec<RequestFilter>),
Or(Vec<RequestFilter>),
Not(Box<RequestFilter>),
Equality(String, String),
}
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
pub struct ListUsersRequest {
pub filters: Option<RequestFilter>,
}
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)] #[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
pub struct UserDetailsRequest { pub struct UserDetailsRequest {
pub user_id: String, pub user_id: String,

View File

@ -4,8 +4,8 @@ use serde::{Deserialize, Serialize};
use std::collections::HashSet; use std::collections::HashSet;
pub use lldap_model::{ pub use lldap_model::{
AddUserToGroupRequest, CreateGroupRequest, CreateUserRequest, DeleteUserRequest, Group, AddUserToGroupRequest, CreateGroupRequest, CreateUserRequest, DeleteUserRequest, Group, User,
ListUsersRequest, RequestFilter, User, UserDetailsRequest, UserDetailsRequest,
}; };
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)] #[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
@ -14,6 +14,14 @@ pub struct BindRequest {
pub password: String, pub password: String,
} }
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
pub enum RequestFilter {
And(Vec<RequestFilter>),
Or(Vec<RequestFilter>),
Not(Box<RequestFilter>),
Equality(String, String),
}
#[async_trait] #[async_trait]
pub trait LoginHandler: Clone + Send { pub trait LoginHandler: Clone + Send {
async fn bind(&self, request: BindRequest) -> Result<()>; async fn bind(&self, request: BindRequest) -> Result<()>;
@ -21,7 +29,7 @@ pub trait LoginHandler: Clone + Send {
#[async_trait] #[async_trait]
pub trait BackendHandler: Clone + Send { pub trait BackendHandler: Clone + Send {
async fn list_users(&self, request: ListUsersRequest) -> Result<Vec<User>>; async fn list_users(&self, filters: Option<RequestFilter>) -> Result<Vec<User>>;
async fn list_groups(&self) -> Result<Vec<Group>>; async fn list_groups(&self) -> Result<Vec<Group>>;
async fn get_user_details(&self, request: UserDetailsRequest) -> Result<User>; async fn get_user_details(&self, request: UserDetailsRequest) -> Result<User>;
async fn create_user(&self, request: CreateUserRequest) -> Result<()>; async fn create_user(&self, request: CreateUserRequest) -> Result<()>;
@ -39,7 +47,7 @@ mockall::mock! {
} }
#[async_trait] #[async_trait]
impl BackendHandler for TestBackendHandler { impl BackendHandler for TestBackendHandler {
async fn list_users(&self, request: ListUsersRequest) -> Result<Vec<User>>; async fn list_users(&self, filters: Option<RequestFilter>) -> Result<Vec<User>>;
async fn list_groups(&self) -> Result<Vec<Group>>; async fn list_groups(&self) -> Result<Vec<Group>>;
async fn get_user_details(&self, request: UserDetailsRequest) -> Result<User>; async fn get_user_details(&self, request: UserDetailsRequest) -> Result<User>;
async fn create_user(&self, request: CreateUserRequest) -> Result<()>; async fn create_user(&self, request: CreateUserRequest) -> Result<()>;

View File

@ -42,7 +42,7 @@ fn get_filter_expr(filter: RequestFilter) -> SimpleExpr {
#[async_trait] #[async_trait]
impl BackendHandler for SqlBackendHandler { impl BackendHandler for SqlBackendHandler {
async fn list_users(&self, request: ListUsersRequest) -> Result<Vec<User>> { async fn list_users(&self, filters: Option<RequestFilter>) -> Result<Vec<User>> {
let query = { let query = {
let mut query_builder = Query::select() let mut query_builder = Query::select()
.column(Users::UserId) .column(Users::UserId)
@ -55,7 +55,7 @@ impl BackendHandler for SqlBackendHandler {
.from(Users::Table) .from(Users::Table)
.order_by(Users::UserId, Order::Asc) .order_by(Users::UserId, Order::Asc)
.to_owned(); .to_owned();
if let Some(filter) = request.filters { if let Some(filter) = filters {
if filter != RequestFilter::And(Vec::new()) if filter != RequestFilter::And(Vec::new())
&& filter != RequestFilter::Or(Vec::new()) && filter != RequestFilter::Or(Vec::new())
{ {
@ -234,6 +234,7 @@ mod tests {
use super::*; use super::*;
use crate::domain::sql_tables::init_table; use crate::domain::sql_tables::init_table;
use crate::infra::configuration::ConfigurationBuilder; use crate::infra::configuration::ConfigurationBuilder;
use lldap_model::{opaque, registration};
fn get_default_config() -> Configuration { fn get_default_config() -> Configuration {
ConfigurationBuilder::default() ConfigurationBuilder::default()
@ -384,7 +385,7 @@ mod tests {
insert_user(&handler, "John", "Pa33w0rd!").await; insert_user(&handler, "John", "Pa33w0rd!").await;
{ {
let users = handler let users = handler
.list_users(ListUsersRequest { filters: None }) .list_users(None)
.await .await
.unwrap() .unwrap()
.into_iter() .into_iter()
@ -394,12 +395,10 @@ mod tests {
} }
{ {
let users = handler let users = handler
.list_users(ListUsersRequest { .list_users(Some(RequestFilter::Equality(
filters: Some(RequestFilter::Equality(
"user_id".to_string(), "user_id".to_string(),
"bob".to_string(), "bob".to_string(),
)), )))
})
.await .await
.unwrap() .unwrap()
.into_iter() .into_iter()
@ -409,12 +408,10 @@ mod tests {
} }
{ {
let users = handler let users = handler
.list_users(ListUsersRequest { .list_users(Some(RequestFilter::Or(vec![
filters: Some(RequestFilter::Or(vec![
RequestFilter::Equality("user_id".to_string(), "bob".to_string()), RequestFilter::Equality("user_id".to_string(), "bob".to_string()),
RequestFilter::Equality("user_id".to_string(), "John".to_string()), RequestFilter::Equality("user_id".to_string(), "John".to_string()),
])), ])))
})
.await .await
.unwrap() .unwrap()
.into_iter() .into_iter()
@ -424,12 +421,10 @@ mod tests {
} }
{ {
let users = handler let users = handler
.list_users(ListUsersRequest { .list_users(Some(RequestFilter::Not(Box::new(RequestFilter::Equality(
filters: Some(RequestFilter::Not(Box::new(RequestFilter::Equality(
"user_id".to_string(), "user_id".to_string(),
"bob".to_string(), "bob".to_string(),
)))), )))))
})
.await .await
.unwrap() .unwrap()
.into_iter() .into_iter()
@ -540,7 +535,7 @@ mod tests {
.unwrap(); .unwrap();
let users = handler let users = handler
.list_users(ListUsersRequest { filters: None }) .list_users(None)
.await .await
.unwrap() .unwrap()
.into_iter() .into_iter()
@ -565,7 +560,7 @@ mod tests {
.unwrap(); .unwrap();
let users = handler let users = handler
.list_users(ListUsersRequest { filters: None }) .list_users(None)
.await .await
.unwrap() .unwrap()
.into_iter() .into_iter()

View File

@ -1,9 +1,10 @@
use crate::domain::handler::BackendHandler; use crate::domain::handler::BackendHandler;
use juniper::{graphql_object, FieldResult, GraphQLInputObject}; use juniper::{graphql_object, FieldResult, GraphQLInputObject};
use lldap_model::{ListUsersRequest, UserDetailsRequest}; use lldap_model::UserDetailsRequest;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::convert::TryInto; use std::convert::TryInto;
type DomainRequestFilter = crate::domain::handler::RequestFilter;
use super::api::Context; use super::api::Context;
#[derive(PartialEq, Eq, Debug, GraphQLInputObject)] #[derive(PartialEq, Eq, Debug, GraphQLInputObject)]
@ -16,9 +17,9 @@ pub struct RequestFilter {
eq: Option<EqualityConstraint>, eq: Option<EqualityConstraint>,
} }
impl TryInto<lldap_model::RequestFilter> for RequestFilter { impl TryInto<DomainRequestFilter> for RequestFilter {
type Error = String; type Error = String;
fn try_into(self) -> Result<lldap_model::RequestFilter, Self::Error> { fn try_into(self) -> Result<DomainRequestFilter, Self::Error> {
let mut field_count = 0; let mut field_count = 0;
if self.any.is_some() { if self.any.is_some() {
field_count += 1; field_count += 1;
@ -39,24 +40,24 @@ impl TryInto<lldap_model::RequestFilter> for RequestFilter {
return Err("Multiple fields specified in request filter".to_string()); return Err("Multiple fields specified in request filter".to_string());
} }
if let Some(e) = self.eq { if let Some(e) = self.eq {
return Ok(lldap_model::RequestFilter::Equality(e.field, e.value)); return Ok(DomainRequestFilter::Equality(e.field, e.value));
} }
if let Some(c) = self.any { if let Some(c) = self.any {
return Ok(lldap_model::RequestFilter::Or( return Ok(DomainRequestFilter::Or(
c.into_iter() c.into_iter()
.map(TryInto::try_into) .map(TryInto::try_into)
.collect::<Result<Vec<_>, String>>()?, .collect::<Result<Vec<_>, String>>()?,
)); ));
} }
if let Some(c) = self.all { if let Some(c) = self.all {
return Ok(lldap_model::RequestFilter::And( return Ok(DomainRequestFilter::And(
c.into_iter() c.into_iter()
.map(TryInto::try_into) .map(TryInto::try_into)
.collect::<Result<Vec<_>, String>>()?, .collect::<Result<Vec<_>, String>>()?,
)); ));
} }
if let Some(c) = self.not { if let Some(c) = self.not {
return Ok(lldap_model::RequestFilter::Not(Box::new((*c).try_into()?))); return Ok(DomainRequestFilter::Not(Box::new((*c).try_into()?)));
} }
unreachable!(); unreachable!();
} }
@ -108,12 +109,7 @@ impl<Handler: BackendHandler + Sync> Query<Handler> {
} }
Ok(context Ok(context
.handler .handler
.list_users(ListUsersRequest { .list_users(filters.map(TryInto::try_into).transpose()?)
filters: match filters {
None => None,
Some(f) => Some(f.try_into()?),
},
})
.await .await
.map(|v| v.into_iter().map(Into::into).collect())?) .map(|v| v.into_iter().map(Into::into).collect())?)
} }
@ -304,14 +300,13 @@ mod tests {
}"#; }"#;
let mut mock = MockTestBackendHandler::new(); let mut mock = MockTestBackendHandler::new();
use lldap_model::{RequestFilter, User}; use crate::domain::handler::RequestFilter;
use lldap_model::User;
mock.expect_list_users() mock.expect_list_users()
.with(eq(ListUsersRequest { .with(eq(Some(RequestFilter::Or(vec![
filters: Some(RequestFilter::Or(vec![
RequestFilter::Equality("id".to_string(), "bob".to_string()), RequestFilter::Equality("id".to_string(), "bob".to_string()),
RequestFilter::Equality("email".to_string(), "robert@bobbers.on".to_string()), RequestFilter::Equality("email".to_string(), "robert@bobbers.on".to_string()),
])), ]))))
}))
.return_once(|_| { .return_once(|_| {
Ok(vec![ Ok(vec![
User { User {

View File

@ -1,4 +1,4 @@
use crate::domain::handler::{BackendHandler, ListUsersRequest, LoginHandler, RequestFilter, User}; use crate::domain::handler::{BackendHandler, LoginHandler, RequestFilter, User};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use ldap3_server::simple::*; use ldap3_server::simple::*;
@ -226,11 +226,7 @@ impl<Backend: BackendHandler + LoginHandler> LdapHandler<Backend> {
)] )]
} }
}; };
let users = match self let users = match self.backend_handler.list_users(filters).await {
.backend_handler
.list_users(ListUsersRequest { filters })
.await
{
Ok(users) => users, Ok(users) => users,
Err(e) => { Err(e) => {
return vec![lsr.gen_error( return vec![lsr.gen_error(
@ -591,14 +587,12 @@ mod tests {
async fn test_search_filters() { async fn test_search_filters() {
let mut mock = MockTestBackendHandler::new(); let mut mock = MockTestBackendHandler::new();
mock.expect_list_users() mock.expect_list_users()
.with(eq(ListUsersRequest { .with(eq(Some(RequestFilter::And(vec![RequestFilter::Or(vec![
filters: Some(RequestFilter::And(vec![RequestFilter::Or(vec![
RequestFilter::Not(Box::new(RequestFilter::Equality( RequestFilter::Not(Box::new(RequestFilter::Equality(
"user_id".to_string(), "user_id".to_string(),
"bob".to_string(), "bob".to_string(),
))), ))),
])])), ])]))))
}))
.times(1) .times(1)
.return_once(|_| Ok(vec![])); .return_once(|_| Ok(vec![]));
let mut ldap_handler = setup_bound_handler(mock).await; let mut ldap_handler = setup_bound_handler(mock).await;

View File

@ -26,7 +26,7 @@ mockall::mock! {
} }
#[async_trait] #[async_trait]
impl BackendHandler for TestTcpBackendHandler { impl BackendHandler for TestTcpBackendHandler {
async fn list_users(&self, request: ListUsersRequest) -> DomainResult<Vec<User>>; async fn list_users(&self, filters: Option<RequestFilter>) -> DomainResult<Vec<User>>;
async fn list_groups(&self) -> DomainResult<Vec<Group>>; async fn list_groups(&self) -> DomainResult<Vec<Group>>;
async fn get_user_details(&self, request: UserDetailsRequest) -> DomainResult<User>; async fn get_user_details(&self, request: UserDetailsRequest) -> DomainResult<User>;
async fn get_user_groups(&self, user: &str) -> DomainResult<HashSet<String>>; async fn get_user_groups(&self, user: &str) -> DomainResult<HashSet<String>>;