feat: Type-erase Database backend for simpler code
This commit is contained in:
parent
9933990fd3
commit
ccbd97b836
17 changed files with 108 additions and 117 deletions
12
Cargo.lock
generated
12
Cargo.lock
generated
|
|
@ -39,6 +39,17 @@ dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "async-trait"
|
||||||
|
version = "0.1.92"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.4",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "atomic-waker"
|
name = "atomic-waker"
|
||||||
version = "1.1.2"
|
version = "1.1.2"
|
||||||
|
|
@ -523,6 +534,7 @@ name = "llldap"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argh",
|
"argh",
|
||||||
|
"async-trait",
|
||||||
"axum",
|
"axum",
|
||||||
"axum-extra",
|
"axum-extra",
|
||||||
"camino",
|
"camino",
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
argh = "0.1.19"
|
argh = "0.1.19"
|
||||||
|
async-trait = "0.1.92"
|
||||||
axum = { version = "0.8.9", optional = true, features = ["macros"] }
|
axum = { version = "0.8.9", optional = true, features = ["macros"] }
|
||||||
axum-extra = { version = "0.12.6", features = ["cookie"], optional = true }
|
axum-extra = { version = "0.12.6", features = ["cookie"], optional = true }
|
||||||
camino = { version = "1.2.5", features = ["serde1"] }
|
camino = { version = "1.2.5", features = ["serde1"] }
|
||||||
|
|
|
||||||
|
|
@ -6,19 +6,19 @@ use crate::db::error::BoxedError;
|
||||||
use crate::db::{DatabaseInterface, Domain, User, UserRef};
|
use crate::db::{DatabaseInterface, Domain, User, UserRef};
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Database<D: DatabaseInterface> {
|
pub struct Database {
|
||||||
pub inner: Arc<RwLock<D>>,
|
pub inner: Arc<RwLock<Box<dyn DatabaseInterface>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<D: DatabaseInterface> Database<D> {
|
impl Database {
|
||||||
pub fn new(db: D) -> Self {
|
pub fn new(db: impl DatabaseInterface) -> Self {
|
||||||
Self {
|
Self {
|
||||||
inner: Arc::new(RwLock::new(db)),
|
inner: Arc::new(RwLock::new(Box::new(db))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<D: DatabaseInterface> Database<D> {
|
impl Database {
|
||||||
/// Return false if the user doesn't exist, or the password is wrong.
|
/// Return false if the user doesn't exist, or the password is wrong.
|
||||||
///
|
///
|
||||||
/// TODO: should we return something else when the account doesn't exist?
|
/// TODO: should we return something else when the account doesn't exist?
|
||||||
|
|
|
||||||
|
|
@ -45,7 +45,7 @@ pub struct FilesystemDatabase {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FilesystemDatabase {
|
impl FilesystemDatabase {
|
||||||
pub async fn from_path(path: impl AsRef<Utf8Path>) -> Result<Database<Self>, BoxedError> {
|
pub async fn from_path(path: impl AsRef<Utf8Path>) -> Result<Database, BoxedError> {
|
||||||
let path = path.as_ref();
|
let path = path.as_ref();
|
||||||
let s = tokio::fs::read(path)
|
let s = tokio::fs::read(path)
|
||||||
.await
|
.await
|
||||||
|
|
@ -67,6 +67,7 @@ impl FilesystemDatabase {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
impl DatabaseInterface for FilesystemDatabase {
|
impl DatabaseInterface for FilesystemDatabase {
|
||||||
async fn create_domain(
|
async fn create_domain(
|
||||||
&mut self,
|
&mut self,
|
||||||
|
|
@ -84,15 +85,12 @@ impl DatabaseInterface for FilesystemDatabase {
|
||||||
Ok(Ok(()))
|
Ok(Ok(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_domain(&self, domain: &str) -> impl Future<Output = Result<Option<Domain>, BoxedError>> {
|
async fn get_domain(&self, domain: &str) -> Result<Option<Domain>, BoxedError> {
|
||||||
self.inner.get_domain(domain)
|
self.inner.get_domain(domain).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_user(
|
async fn get_user(&self, req_user: &UserRef) -> Result<Option<User>, BoxedError> {
|
||||||
&self,
|
self.inner.get_user(req_user).await
|
||||||
req_user: &UserRef,
|
|
||||||
) -> impl Future<Output = Result<Option<User>, BoxedError>> {
|
|
||||||
self.inner.get_user(req_user)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_user(
|
async fn create_user(
|
||||||
|
|
@ -128,18 +126,15 @@ impl DatabaseInterface for FilesystemDatabase {
|
||||||
Ok(Ok(()))
|
Ok(Ok(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_all_domains(&self) -> impl Future<Output = Result<Vec<Domain>, BoxedError>> {
|
async fn list_all_domains(&self) -> Result<Vec<Domain>, BoxedError> {
|
||||||
self.inner.list_all_domains()
|
self.inner.list_all_domains().await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_all_users(&self) -> impl Future<Output = Result<Vec<User>, BoxedError>> {
|
async fn list_all_users(&self) -> Result<Vec<User>, BoxedError> {
|
||||||
self.inner.list_all_users()
|
self.inner.list_all_users().await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_domain_users(
|
async fn list_domain_users(&self, domain: Option<String>) -> Result<Vec<User>, BoxedError> {
|
||||||
&self,
|
self.inner.list_domain_users(domain).await
|
||||||
domain: Option<String>,
|
|
||||||
) -> impl Future<Output = Result<Vec<User>, BoxedError>> {
|
|
||||||
self.inner.list_domain_users(domain)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
use crate::db::error::{BoxedError, DomainCreationError, UserCreationError};
|
use crate::db::error::{BoxedError, DomainCreationError, UserCreationError};
|
||||||
use crate::db::{Database, Domain, User, UserRef};
|
use crate::db::{Database, Domain, User, UserRef};
|
||||||
|
|
||||||
impl<D: DatabaseInterface> DatabaseInterface for Database<D> {
|
#[async_trait::async_trait]
|
||||||
|
impl DatabaseInterface for Database {
|
||||||
async fn create_domain(
|
async fn create_domain(
|
||||||
&mut self,
|
&mut self,
|
||||||
domain: &str,
|
domain: &str,
|
||||||
|
|
@ -49,39 +50,31 @@ impl<D: DatabaseInterface> DatabaseInterface for Database<D> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait DatabaseInterface: Clone + Send + Sync + 'static {
|
#[async_trait::async_trait]
|
||||||
fn create_domain(
|
pub trait DatabaseInterface: std::fmt::Debug + Send + Sync + 'static {
|
||||||
|
async fn create_domain(
|
||||||
&mut self,
|
&mut self,
|
||||||
domain: &str,
|
domain: &str,
|
||||||
) -> impl Future<Output = Result<Result<(), DomainCreationError>, BoxedError>> + Send;
|
) -> Result<Result<(), DomainCreationError>, BoxedError>;
|
||||||
fn get_domain(
|
async fn get_domain(&self, domain: &str) -> Result<Option<Domain>, BoxedError>;
|
||||||
&self,
|
|
||||||
domain: &str,
|
|
||||||
) -> impl Future<Output = Result<Option<Domain>, BoxedError>> + Send;
|
|
||||||
|
|
||||||
fn get_user(
|
async fn get_user(&self, user: &UserRef) -> Result<Option<User>, BoxedError>;
|
||||||
&self,
|
|
||||||
user: &UserRef,
|
|
||||||
) -> impl Future<Output = Result<Option<User>, BoxedError>> + Send;
|
|
||||||
async fn create_user(
|
async fn create_user(
|
||||||
&mut self,
|
&mut self,
|
||||||
user: User,
|
user: User,
|
||||||
) -> Result<Result<(), UserCreationError>, BoxedError>;
|
) -> Result<Result<(), UserCreationError>, BoxedError>;
|
||||||
fn try_create_user(
|
async fn try_create_user(
|
||||||
&mut self,
|
&mut self,
|
||||||
new_user: User,
|
new_user: User,
|
||||||
current_user: &User,
|
current_user: &User,
|
||||||
) -> impl Future<Output = Result<Result<(), UserCreationError>, BoxedError>> + Send;
|
) -> Result<Result<(), UserCreationError>, BoxedError>;
|
||||||
|
|
||||||
fn list_all_domains(&self) -> impl Future<Output = Result<Vec<Domain>, BoxedError>> + Send;
|
async fn list_all_domains(&self) -> Result<Vec<Domain>, BoxedError>;
|
||||||
#[expect(unused)]
|
#[expect(unused)]
|
||||||
fn list_all_users(&self) -> impl Future<Output = Result<Vec<User>, BoxedError>> + Send;
|
async fn list_all_users(&self) -> Result<Vec<User>, BoxedError>;
|
||||||
|
|
||||||
/// List users on a specific domain.
|
/// List users on a specific domain.
|
||||||
///
|
///
|
||||||
/// A `None` domain requested lists global service users.
|
/// A `None` domain requested lists global service users.
|
||||||
fn list_domain_users(
|
async fn list_domain_users(&self, domain: Option<String>) -> Result<Vec<User>, BoxedError>;
|
||||||
&self,
|
|
||||||
domain: Option<String>,
|
|
||||||
) -> impl Future<Output = Result<Vec<User>, BoxedError>> + Send;
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,5 @@
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use std::future::ready;
|
|
||||||
|
|
||||||
use crate::db::error::{BoxedError, DomainCreationError, UserCreationError};
|
use crate::db::error::{BoxedError, DomainCreationError, UserCreationError};
|
||||||
use crate::db::{Database, DatabaseInterface, Domain, Group, Operation, User, UserRef};
|
use crate::db::{Database, DatabaseInterface, Domain, Group, Operation, User, UserRef};
|
||||||
|
|
||||||
|
|
@ -14,52 +12,49 @@ pub struct MemoryDatabase {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MemoryDatabase {
|
impl MemoryDatabase {
|
||||||
pub fn new() -> Database<Self> {
|
#[allow(clippy::new_ret_no_self)]
|
||||||
|
pub fn new() -> Database {
|
||||||
Database::new(Self::default())
|
Database::new(Self::default())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
impl DatabaseInterface for MemoryDatabase {
|
impl DatabaseInterface for MemoryDatabase {
|
||||||
fn create_domain(
|
async fn create_domain(
|
||||||
&mut self,
|
&mut self,
|
||||||
domain: &str,
|
domain: &str,
|
||||||
) -> impl Future<Output = Result<Result<(), DomainCreationError>, BoxedError>> {
|
) -> Result<Result<(), DomainCreationError>, BoxedError> {
|
||||||
if domain.is_empty() {
|
if domain.is_empty() {
|
||||||
return ready(Ok(Err(DomainCreationError::InvalidDomain(
|
return Ok(Err(DomainCreationError::InvalidDomain(domain.to_string())));
|
||||||
domain.to_string(),
|
|
||||||
))));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.domains.iter().find(|d| d.name == domain).is_some() {
|
if self.domains.iter().find(|d| d.name == domain).is_some() {
|
||||||
return ready(Ok(Err(DomainCreationError::DomainAlreadyExists(
|
return Ok(Err(DomainCreationError::DomainAlreadyExists(
|
||||||
domain.to_string(),
|
domain.to_string(),
|
||||||
))));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
self.domains.push(Domain {
|
self.domains.push(Domain {
|
||||||
name: domain.to_string(),
|
name: domain.to_string(),
|
||||||
});
|
});
|
||||||
|
|
||||||
ready(Ok(Ok(())))
|
Ok(Ok(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_domain(&self, domain: &str) -> impl Future<Output = Result<Option<Domain>, BoxedError>> {
|
async fn get_domain(&self, domain: &str) -> Result<Option<Domain>, BoxedError> {
|
||||||
let Some(domain) = self.domains.iter().find(|d| d.name == domain) else {
|
let Some(domain) = self.domains.iter().find(|d| d.name == domain) else {
|
||||||
return ready(Ok(None));
|
return Ok(None);
|
||||||
};
|
};
|
||||||
|
|
||||||
ready(Ok(Some(domain.clone())))
|
Ok(Some(domain.clone()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_user(
|
async fn get_user(&self, req_user: &UserRef) -> Result<Option<User>, BoxedError> {
|
||||||
&self,
|
Ok(self
|
||||||
req_user: &UserRef,
|
|
||||||
) -> impl Future<Output = Result<Option<User>, BoxedError>> {
|
|
||||||
ready(Ok(self
|
|
||||||
.users
|
.users
|
||||||
.iter()
|
.iter()
|
||||||
.find(|u| u.username == req_user.username && u.domain == req_user.domain)
|
.find(|u| u.username == req_user.username && u.domain == req_user.domain)
|
||||||
.cloned()))
|
.cloned())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_user(
|
async fn create_user(
|
||||||
|
|
@ -104,23 +99,20 @@ impl DatabaseInterface for MemoryDatabase {
|
||||||
self.create_user(new_user).await
|
self.create_user(new_user).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_all_domains(&self) -> impl Future<Output = Result<Vec<Domain>, BoxedError>> {
|
async fn list_all_domains(&self) -> Result<Vec<Domain>, BoxedError> {
|
||||||
ready(Ok(self.domains.clone()))
|
Ok(self.domains.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_all_users(&self) -> impl Future<Output = Result<Vec<User>, BoxedError>> {
|
async fn list_all_users(&self) -> Result<Vec<User>, BoxedError> {
|
||||||
ready(Ok(self.users.clone()))
|
Ok(self.users.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_domain_users(
|
async fn list_domain_users(&self, domain: Option<String>) -> Result<Vec<User>, BoxedError> {
|
||||||
&self,
|
Ok(self
|
||||||
domain: Option<String>,
|
|
||||||
) -> impl Future<Output = Result<Vec<User>, BoxedError>> {
|
|
||||||
ready(Ok(self
|
|
||||||
.users
|
.users
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|u| u.domain == domain)
|
.filter(|u| u.domain == domain)
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect()))
|
.collect())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,8 @@ use serde::Deserialize;
|
||||||
use crate::db::{DatabaseInterface, Operation};
|
use crate::db::{DatabaseInterface, Operation};
|
||||||
use crate::http::{HttpSession, HttpState};
|
use crate::http::{HttpSession, HttpState};
|
||||||
|
|
||||||
pub async fn get_domain<D: DatabaseInterface>(
|
pub async fn get_domain(
|
||||||
State(state): State<HttpState<D>>,
|
State(state): State<HttpState>,
|
||||||
session: HttpSession,
|
session: HttpSession,
|
||||||
Path(domain): Path<String>,
|
Path(domain): Path<String>,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
|
|
@ -53,8 +53,8 @@ pub struct DomainCreationForm {
|
||||||
domainname: String,
|
domainname: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn create_domain<D: DatabaseInterface>(
|
pub async fn create_domain(
|
||||||
State(mut state): State<HttpState<D>>,
|
State(mut state): State<HttpState>,
|
||||||
session: HttpSession,
|
session: HttpSession,
|
||||||
Form(form): Form<DomainCreationForm>,
|
Form(form): Form<DomainCreationForm>,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,8 @@ use minijinja::context;
|
||||||
use crate::db::{DatabaseInterface, Operation};
|
use crate::db::{DatabaseInterface, Operation};
|
||||||
use crate::http::{HttpSession, HttpState};
|
use crate::http::{HttpSession, HttpState};
|
||||||
|
|
||||||
pub async fn home<D: DatabaseInterface>(
|
pub async fn home(
|
||||||
State(state): State<HttpState<D>>,
|
State(state): State<HttpState>,
|
||||||
// Only logged in users are allowed here
|
// Only logged in users are allowed here
|
||||||
session: HttpSession,
|
session: HttpSession,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
|
|
|
||||||
|
|
@ -20,8 +20,8 @@ pub enum LoginError {
|
||||||
SessionInvalidated,
|
SessionInvalidated,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn login_page<D: DatabaseInterface>(
|
pub async fn login_page(
|
||||||
State(state): State<HttpState<D>>,
|
State(state): State<HttpState>,
|
||||||
login_error: Option<LoginError>,
|
login_error: Option<LoginError>,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let page = state
|
let page = state
|
||||||
|
|
@ -33,8 +33,8 @@ pub async fn login_page<D: DatabaseInterface>(
|
||||||
(StatusCode::OK, Html(page)).into_response()
|
(StatusCode::OK, Html(page)).into_response()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_login<D: DatabaseInterface>(
|
pub async fn get_login(
|
||||||
State(state): State<HttpState<D>>,
|
State(state): State<HttpState>,
|
||||||
maybe_session: Option<OptionalHttpSession>,
|
maybe_session: Option<OptionalHttpSession>,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
if maybe_session.is_some() {
|
if maybe_session.is_some() {
|
||||||
|
|
@ -44,8 +44,8 @@ pub async fn get_login<D: DatabaseInterface>(
|
||||||
login_page(State(state), None).await
|
login_page(State(state), None).await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn post_login<D: DatabaseInterface>(
|
pub async fn post_login(
|
||||||
State(state): State<HttpState<D>>,
|
State(state): State<HttpState>,
|
||||||
session: Option<OptionalHttpSession>,
|
session: Option<OptionalHttpSession>,
|
||||||
cookies: CookieJar,
|
cookies: CookieJar,
|
||||||
Form(form): Form<LoginForm>,
|
Form(form): Form<LoginForm>,
|
||||||
|
|
|
||||||
|
|
@ -2,12 +2,11 @@ use axum::extract::State;
|
||||||
use axum::response::{IntoResponse, Redirect, Response};
|
use axum::response::{IntoResponse, Redirect, Response};
|
||||||
use axum_extra::extract::cookie::CookieJar;
|
use axum_extra::extract::cookie::CookieJar;
|
||||||
|
|
||||||
use crate::db::DatabaseInterface;
|
|
||||||
use crate::http::login::{LoginError, login_page};
|
use crate::http::login::{LoginError, login_page};
|
||||||
use crate::http::{HttpState, OptionalHttpSession};
|
use crate::http::{HttpState, OptionalHttpSession};
|
||||||
|
|
||||||
pub async fn logout<D: DatabaseInterface>(
|
pub async fn logout(
|
||||||
State(state): State<HttpState<D>>,
|
State(state): State<HttpState>,
|
||||||
session: Option<OptionalHttpSession>,
|
session: Option<OptionalHttpSession>,
|
||||||
cookies: CookieJar,
|
cookies: CookieJar,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ use static_serve::embed_assets;
|
||||||
#[cfg(not(feature = "embed"))]
|
#[cfg(not(feature = "embed"))]
|
||||||
use tower_http::services::ServeDir;
|
use tower_http::services::ServeDir;
|
||||||
|
|
||||||
use crate::db::{Database, DatabaseInterface};
|
use crate::db::Database;
|
||||||
use crate::listener::{Listener, ListenerKind};
|
use crate::listener::{Listener, ListenerKind};
|
||||||
use crate::stream::{AbstractSocketAddr, AbstractStreamKind};
|
use crate::stream::{AbstractSocketAddr, AbstractStreamKind};
|
||||||
|
|
||||||
|
|
@ -62,14 +62,14 @@ impl AxumListener for Listener {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct HttpState<D: DatabaseInterface> {
|
pub struct HttpState {
|
||||||
pub db: Database<D>,
|
pub db: Database,
|
||||||
pub sessions: HttpSessionManager,
|
pub sessions: HttpSessionManager,
|
||||||
pub templates: Environment<'static>,
|
pub templates: Environment<'static>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<D: DatabaseInterface> HttpState<D> {
|
impl HttpState {
|
||||||
pub fn new(db: Database<D>) -> Self {
|
pub fn new(db: Database) -> Self {
|
||||||
let mut templates = Environment::new();
|
let mut templates = Environment::new();
|
||||||
#[cfg(feature = "embed")]
|
#[cfg(feature = "embed")]
|
||||||
minijinja_embed::load_templates!(&mut templates);
|
minijinja_embed::load_templates!(&mut templates);
|
||||||
|
|
@ -83,7 +83,7 @@ impl<D: DatabaseInterface> HttpState<D> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn http_listen<D: DatabaseInterface>(listener: Listener, db: Database<D>) {
|
pub async fn http_listen(listener: Listener, db: Database) {
|
||||||
#[cfg(all(feature = "embed", feature = "noembed"))]
|
#[cfg(all(feature = "embed", feature = "noembed"))]
|
||||||
compile_error!("You cannot have `embed` and `noembed` features enabled at the same time.");
|
compile_error!("You cannot have `embed` and `noembed` features enabled at the same time.");
|
||||||
#[cfg(not(any(feature = "embed", feature = "noembed")))]
|
#[cfg(not(any(feature = "embed", feature = "noembed")))]
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ use uuid::Uuid;
|
||||||
|
|
||||||
use std::sync::{Arc, RwLock};
|
use std::sync::{Arc, RwLock};
|
||||||
|
|
||||||
use crate::db::{DatabaseInterface, User};
|
use crate::db::User;
|
||||||
use crate::http::HttpState;
|
use crate::http::HttpState;
|
||||||
|
|
||||||
pub const COOKIE_NAME: &str = "lldap_session";
|
pub const COOKIE_NAME: &str = "lldap_session";
|
||||||
|
|
@ -83,12 +83,12 @@ impl PartialEq<HttpSession> for HttpSession {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<D: DatabaseInterface> FromRequestParts<HttpState<D>> for HttpSession {
|
impl FromRequestParts<HttpState> for HttpSession {
|
||||||
type Rejection = Redirect;
|
type Rejection = Redirect;
|
||||||
|
|
||||||
async fn from_request_parts(
|
async fn from_request_parts(
|
||||||
parts: &mut Parts,
|
parts: &mut Parts,
|
||||||
state: &HttpState<D>,
|
state: &HttpState,
|
||||||
) -> Result<Self, Self::Rejection> {
|
) -> Result<Self, Self::Rejection> {
|
||||||
let cookies = CookieJar::from_request_parts(parts, state).await.unwrap();
|
let cookies = CookieJar::from_request_parts(parts, state).await.unwrap();
|
||||||
state
|
state
|
||||||
|
|
@ -108,12 +108,12 @@ impl std::ops::Deref for OptionalHttpSession {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<D: DatabaseInterface> OptionalFromRequestParts<HttpState<D>> for OptionalHttpSession {
|
impl OptionalFromRequestParts<HttpState> for OptionalHttpSession {
|
||||||
type Rejection = Redirect;
|
type Rejection = Redirect;
|
||||||
|
|
||||||
async fn from_request_parts(
|
async fn from_request_parts(
|
||||||
parts: &mut Parts,
|
parts: &mut Parts,
|
||||||
state: &HttpState<D>,
|
state: &HttpState,
|
||||||
) -> Result<Option<Self>, Self::Rejection> {
|
) -> Result<Option<Self>, Self::Rejection> {
|
||||||
let maybe_session = HttpSession::from_request_parts(parts, state)
|
let maybe_session = HttpSession::from_request_parts(parts, state)
|
||||||
.await
|
.await
|
||||||
|
|
|
||||||
|
|
@ -12,8 +12,8 @@ pub struct UserCreationForm {
|
||||||
pub password: String,
|
pub password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn create_user<D: DatabaseInterface>(
|
pub async fn create_user(
|
||||||
State(mut state): State<HttpState<D>>,
|
State(mut state): State<HttpState>,
|
||||||
session: HttpSession,
|
session: HttpSession,
|
||||||
Form(form): Form<UserCreationForm>,
|
Form(form): Form<UserCreationForm>,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,13 @@
|
||||||
use ldap3_proto::LdapMsg;
|
use ldap3_proto::LdapMsg;
|
||||||
use ldap3_proto::proto::LdapOp;
|
use ldap3_proto::proto::LdapOp;
|
||||||
|
|
||||||
use crate::db::{Database, DatabaseInterface};
|
use crate::db::Database;
|
||||||
use crate::ldap::{
|
use crate::ldap::{
|
||||||
LdapClientState, LdapStream, LdapStreamError, op_bind, op_ext, search_by_mail_filter,
|
LdapClientState, LdapStream, LdapStreamError, op_bind, op_ext, search_by_mail_filter,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[tracing::instrument(name = "ldap", skip(stream, db), fields(session = %stream.session))]
|
#[tracing::instrument(name = "ldap", skip(stream, db), fields(session = %stream.session))]
|
||||||
pub async fn ldap_handler<D: DatabaseInterface>(mut stream: LdapStream, mut db: Database<D>) {
|
pub async fn ldap_handler(mut stream: LdapStream, mut db: Database) {
|
||||||
tracing::info! {
|
tracing::info! {
|
||||||
remote_addr = ?stream.remote_addr,
|
remote_addr = ?stream.remote_addr,
|
||||||
"New client connection"
|
"New client connection"
|
||||||
|
|
@ -45,11 +45,11 @@ pub async fn ldap_handler<D: DatabaseInterface>(mut stream: LdapStream, mut db:
|
||||||
|
|
||||||
/// Return true to keep the connection going, false to close it.
|
/// Return true to keep the connection going, false to close it.
|
||||||
#[tracing::instrument(name = "ldap-handler", skip(client_state, db, stream))]
|
#[tracing::instrument(name = "ldap-handler", skip(client_state, db, stream))]
|
||||||
pub async fn ldap_handler_inner<D: DatabaseInterface>(
|
pub async fn ldap_handler_inner(
|
||||||
stream: &mut LdapStream,
|
stream: &mut LdapStream,
|
||||||
msg: LdapMsg,
|
msg: LdapMsg,
|
||||||
client_state: &mut LdapClientState,
|
client_state: &mut LdapClientState,
|
||||||
db: &mut Database<D>,
|
db: &mut Database,
|
||||||
) -> Result<bool, LdapStreamError> {
|
) -> Result<bool, LdapStreamError> {
|
||||||
tracing::debug!(msg = ?msg, "Received LDAP message");
|
tracing::debug!(msg = ?msg, "Received LDAP message");
|
||||||
match msg {
|
match msg {
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ use ldap3_proto::proto::{LdapBindCred, LdapBindRequest, LdapBindResponse, LdapOp
|
||||||
use ldap3_proto::{LdapMsg, LdapResultCode};
|
use ldap3_proto::{LdapMsg, LdapResultCode};
|
||||||
|
|
||||||
use crate::db::error::BoxedError;
|
use crate::db::error::BoxedError;
|
||||||
use crate::db::{Database, DatabaseInterface, UserRef};
|
use crate::db::{Database, UserRef};
|
||||||
use crate::ldap::{Dn, LdapReturnError, LdapStream, LdapStreamError, MalformedDn};
|
use crate::ldap::{Dn, LdapReturnError, LdapStream, LdapStreamError, MalformedDn};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
|
@ -165,9 +165,9 @@ pub async fn bind_success(stream: &mut LdapStream, msgid: i32) -> Result<(), Lda
|
||||||
///
|
///
|
||||||
/// On success, returns `Ok(Some(bound_dn))`. `Ok(None)` means credentials failed,
|
/// On success, returns `Ok(Some(bound_dn))`. `Ok(None)` means credentials failed,
|
||||||
/// either because the account does not exist, or the password is wrong.
|
/// either because the account does not exist, or the password is wrong.
|
||||||
pub async fn op_bind<D: DatabaseInterface>(
|
pub async fn op_bind(
|
||||||
stream: &mut LdapStream,
|
stream: &mut LdapStream,
|
||||||
db: &Database<D>,
|
db: &Database,
|
||||||
req: LdapBindRequest,
|
req: LdapBindRequest,
|
||||||
msgid: i32,
|
msgid: i32,
|
||||||
) -> Result<Option<BindDn>, LdapStreamError> {
|
) -> Result<Option<BindDn>, LdapStreamError> {
|
||||||
|
|
|
||||||
|
|
@ -174,9 +174,9 @@ fn search_entry_from_user(user: &User, req_attrs: &[String]) -> LdapSearchResult
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn search_by_mail_filter<D: DatabaseInterface>(
|
pub async fn search_by_mail_filter(
|
||||||
stream: &mut LdapStream,
|
stream: &mut LdapStream,
|
||||||
db: &Database<D>,
|
db: &Database,
|
||||||
sr: LdapSearchRequest,
|
sr: LdapSearchRequest,
|
||||||
msgid: i32,
|
msgid: i32,
|
||||||
) -> Result<(), LdapStreamError> {
|
) -> Result<(), LdapStreamError> {
|
||||||
|
|
|
||||||
13
src/main.rs
13
src/main.rs
|
|
@ -17,7 +17,7 @@ use error::GlobalError;
|
||||||
use ldap::ldap_handler;
|
use ldap::ldap_handler;
|
||||||
use listener::ListenerPath;
|
use listener::ListenerPath;
|
||||||
|
|
||||||
async fn create_dummy_users<D: DatabaseInterface>(db: &mut Database<D>) {
|
async fn create_dummy_users(db: &mut Database) {
|
||||||
db.create_user(User {
|
db.create_user(User {
|
||||||
username: "admin".to_string(),
|
username: "admin".to_string(),
|
||||||
domain: None,
|
domain: None,
|
||||||
|
|
@ -69,12 +69,11 @@ async fn main() -> Result<(), GlobalError> {
|
||||||
|
|
||||||
let ldap_listener = ListenerPath::new(&cli.listen_ldap)?.listener().await?;
|
let ldap_listener = ListenerPath::new(&cli.listen_ldap)?.listener().await?;
|
||||||
|
|
||||||
// let mut db = if let Some(db_path) = &cli.db {
|
let mut db = if let Some(db_path) = &cli.db {
|
||||||
// FilesystemDatabase::from_path(db_path).await.unwrap()
|
FilesystemDatabase::from_path(db_path).await.unwrap()
|
||||||
// } else {
|
} else {
|
||||||
// MemoryDatabase::new()
|
MemoryDatabase::new()
|
||||||
// };
|
};
|
||||||
let mut db = MemoryDatabase::new();
|
|
||||||
create_dummy_users(&mut db).await;
|
create_dummy_users(&mut db).await;
|
||||||
|
|
||||||
#[cfg(feature = "http")]
|
#[cfg(feature = "http")]
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue