refactor: HttpSession/OptionalHttpSession axum extractors

This commit is contained in:
selfhoster selfhoster 2026-09-19 12:30:47 +02:00
commit 44c083a8ef
7 changed files with 111 additions and 81 deletions

View file

@ -1,9 +1,13 @@
use axum::extract::{FromRequestParts, OptionalFromRequestParts};
use axum::response::Redirect;
use axum_extra::extract::cookie::{Cookie, CookieJar};
use http::request::Parts;
use uuid::Uuid;
use std::sync::{Arc, RwLock};
use crate::db::User;
use crate::db::{DatabaseInterface, User};
use crate::http::HttpState;
pub const COOKIE_NAME: &str = "lldap_session";
@ -78,3 +82,43 @@ impl PartialEq<HttpSession> for HttpSession {
self.uuid == other.uuid
}
}
impl<D: DatabaseInterface> FromRequestParts<HttpState<D>> for HttpSession {
type Rejection = Redirect;
async fn from_request_parts(
parts: &mut Parts,
state: &HttpState<D>,
) -> Result<Self, Self::Rejection> {
let cookies = CookieJar::from_request_parts(parts, state).await.unwrap();
state
.sessions
.get_session(&cookies)
.ok_or(Redirect::to("/login"))
}
}
pub struct OptionalHttpSession(pub HttpSession);
impl std::ops::Deref for OptionalHttpSession {
type Target = HttpSession;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<D: DatabaseInterface> OptionalFromRequestParts<HttpState<D>> for OptionalHttpSession {
type Rejection = Redirect;
async fn from_request_parts(
parts: &mut Parts,
state: &HttpState<D>,
) -> Result<Option<Self>, Self::Rejection> {
let maybe_session = HttpSession::from_request_parts(parts, state)
.await
.ok()
.map(Self);
Ok(maybe_session)
}
}