llldap/src/http/session.rs

124 lines
3.1 KiB
Rust
Raw Normal View History

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::{DatabaseInterface, User};
use crate::http::HttpState;
2026-09-08 16:39:50 +02:00
pub const COOKIE_NAME: &str = "lldap_session";
#[derive(Clone, Debug)]
pub struct HttpSessionManager {
inner: Arc<RwLock<Vec<HttpSession>>>,
}
impl HttpSessionManager {
pub fn new() -> Self {
Self {
inner: Arc::new(RwLock::new(vec![])),
}
}
2026-09-08 16:39:50 +02:00
pub fn add_session(&self, user: User, cookies: CookieJar) -> CookieJar {
let uuid = Uuid::new_v4();
let mut cookie = Cookie::new(COOKIE_NAME, uuid.to_string());
cookie.set_path("/");
2026-09-08 16:39:50 +02:00
let session = HttpSession { user, uuid };
{
self.inner.write().unwrap().push(session);
}
cookies.add(cookie)
}
pub fn get_session(&self, cookies: &CookieJar) -> Option<HttpSession> {
let cookie = cookies.get(COOKIE_NAME)?;
let previous_uuid = Uuid::parse_str(cookie.value()).ok()?;
self.inner
.read()
.unwrap()
.iter()
.find(|session| session.uuid == previous_uuid)
.cloned()
}
pub fn remove_session(&self, session: &HttpSession, cookies: CookieJar) -> CookieJar {
let mut cookie = Cookie::new(COOKIE_NAME, String::new());
cookie.set_path("/");
let idx = {
let Some(idx) = self.inner.read().unwrap().iter().position(|s| s == session) else {
return cookies;
};
idx
};
{
self.inner.write().unwrap().remove(idx);
}
cookies.remove(cookie)
}
}
2026-09-08 16:39:50 +02:00
#[derive(Clone, Debug)]
pub struct HttpSession {
2026-09-08 16:39:50 +02:00
// TODO: by storing the session here, it means
// it needs to be updated every time we change the user.
pub user: User,
pub uuid: Uuid,
}
2026-09-08 16:39:50 +02:00
impl PartialEq<HttpSession> for HttpSession {
fn eq(&self, other: &Self) -> bool {
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)
}
}