use crate::guard;
use crate::Authenticatable;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::http::StatusCode;
use larust_core::AppError;
use larust_http::session::Session;
pub struct Auth<U>(pub U);
#[axum::async_trait]
impl<S, U> FromRequestParts<S> for Auth<U>
where
S: Send + Sync,
U: Authenticatable,
{
type Rejection = AppError;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let session = Session::from_request_parts(parts, state)
.await
.map_err(|(_, message)| AppError::Internal(Box::new(std::io::Error::other(message))))?;
guard::user::<U>(&session)
.await?
.map(Auth)
.ok_or_else(|| AppError::Http {
status: StatusCode::UNAUTHORIZED,
message: "Unauthenticated.".to_string(),
})
}
}