lmrc-cli 0.3.16

CLI tool for scaffolding LMRC Stack infrastructure projects
Documentation
//! Infrastructure authentication middleware

use axum::{
    extract::{Request, State},
    http::StatusCode,
    middleware::Next,
    response::Response,
};
use cookie::Cookie;

use crate::error::AppError;
use crate::state::AppState;

/// Middleware to validate infrastructure sessions
pub async fn infra_auth_middleware(
    State(state): State<AppState>,
    mut request: Request,
    next: Next,
) -> Result<Response, AppError> {
    // Extract session token from cookie
    let headers = request.headers();
    let cookie_header = headers
        .get("cookie")
        .and_then(|value| value.to_str().ok())
        .unwrap_or("");

    let session_token = Cookie::split_parse(cookie_header)
        .filter_map(|cookie| cookie.ok())
        .find(|cookie| cookie.name() == "infra_session")
        .map(|cookie| cookie.value().to_string());

    let session_token = session_token.ok_or_else(|| {
        AppError::Unauthorized("Missing session token".to_string())
    })?;

    // Validate session
    let user = state
        .infra_auth
        .validate_session(&session_token)
        .await?
        .ok_or_else(|| AppError::Unauthorized("Invalid or expired session".to_string()))?;

    // Attach user and session token to request
    request.extensions_mut().insert(user);
    request.extensions_mut().insert(session_token);

    Ok(next.run(request).await)
}