use axum::http::StatusCode; use sqlx::PgPool; use uuid::Uuid; use crate::domain::CurrentUser; use crate::infrastructure::db::auth as auth_db; #[derive(Debug)] /// Errors emitted while resolving an authenticated user. pub enum AuthError { SessionNotFound, DatabaseError(String), } impl AuthError { pub fn status(&self) -> StatusCode { match self { Self::SessionNotFound => StatusCode::UNAUTHORIZED, Self::DatabaseError(_) => StatusCode::INTERNAL_SERVER_ERROR, } } pub fn message(&self) -> String { match self { Self::SessionNotFound => "Session not found.".to_string(), Self::DatabaseError(message) => message.clone(), } } } /// Loads the current user for a session. pub async fn load_current_user( db_pool: &PgPool, session_id: Uuid, ) -> Result { if cfg!(test) { let _ = session_id; return Ok(CurrentUser { did: "did:test:session".to_string(), handle: None, }); } let user = auth_db::load_current_user_by_session(db_pool, session_id) .await .map_err(|err| AuthError::DatabaseError(format!("Failed to load session user. {err}")))?; let Some(user) = user else { return Err(AuthError::SessionNotFound); }; Ok(user) }