use crate::users::{User, UserRepository}; use axum::extract::FromRef; use axum::extract::FromRequestParts; use axum::http::StatusCode; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; use sqlx::SqlitePool; use std::sync::Arc; pub struct AuthUser(pub User); impl FromRequestParts for AuthUser where Arc: axum::extract::FromRef, S: Send + Sync, { type Rejection = Response; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { let pool = Arc::::from_ref(state); let auth_header = parts .headers .get("authorization") .and_then(|v| v.to_str().ok()) .and_then(|s| s.strip_prefix("Bearer ")); if let Some(user_id) = auth_header { let repo = UserRepository { db: &pool }; if let Ok(Some(user)) = repo.get_user_by_user_id(user_id).await { return Ok(AuthUser(user)); } } Err((StatusCode::UNAUTHORIZED, "Unauthorized").into_response()) } }