use axum::{
extract::{FromRequest, Json},
response::{IntoResponse, Response},
};
use serde::de::DeserializeOwned;
use wordval_core::api::ApiError;
use wordval_core::error_registry::{error_message_of, ErrorCode};
#[derive(Debug, Clone, Copy, Default)]
pub struct ValidatedJson<T>(pub T);
impl<T, S> FromRequest<S> for ValidatedJson<T>
where
T: DeserializeOwned,
S: Send + Sync,
{
type Rejection = ValidatedJsonRejection;
async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Self::Rejection> {
match Json::<T>::from_request(req, state).await {
Ok(Json(value)) => Ok(ValidatedJson(value)),
Err(rejection) => {
let msg = format!("请求体格式错误: {}", rejection.body_text());
Err(ValidatedJsonRejection(ApiError::bad_request(msg)))
}
}
}
}
impl<T: validator::Validate> ValidatedJson<T> {
pub fn validate(self) -> Result<Self, ApiError> {
self.0.validate().map_err(|e| {
ApiError::unprocessable_entity(wordval_utils::valid::Valid::format_validation_errors(
&e,
))
})?;
Ok(self)
}
}
impl<T> std::ops::Deref for ValidatedJson<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> std::ops::DerefMut for ValidatedJson<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[derive(Debug)]
pub struct ValidatedJsonRejection(pub ApiError);
impl IntoResponse for ValidatedJsonRejection {
fn into_response(self) -> Response {
self.0.into_response()
}
}
impl From<ValidatedJsonRejection> for ApiError {
fn from(rejection: ValidatedJsonRejection) -> Self {
rejection.0
}
}
pub use crate::middleware::CurrentUser;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
impl<S: Send + Sync> FromRequestParts<S> for CurrentUser {
type Rejection = ApiError;
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
parts
.extensions
.get::<CurrentUser>()
.cloned()
.ok_or_else(|| ApiError::unauthorized(error_message_of(ErrorCode::Unauthorized)))
}
}
#[derive(Debug, Clone)]
pub struct OptionalUser(pub Option<CurrentUser>);
impl OptionalUser {
pub fn user_id(&self) -> i64 {
self.0.as_ref().map(|u| u.id).unwrap_or(0)
}
pub fn is_guest(&self) -> bool {
self.0.is_none()
}
}
impl<S: Send + Sync> FromRequestParts<S> for OptionalUser {
type Rejection = ApiError;
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
Ok(OptionalUser(parts.extensions.get::<CurrentUser>().cloned()))
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ClientContext {
pub ip: String,
pub user_agent: Option<String>,
pub started: std::time::Instant,
pub request_id: Option<String>,
}
impl ClientContext {
pub fn elapsed(&self) -> std::time::Duration {
self.started.elapsed()
}
pub fn elapsed_ms(&self) -> u64 {
self.elapsed().as_millis() as u64
}
}
impl<S: Send + Sync> FromRequestParts<S> for ClientContext {
type Rejection = std::convert::Infallible;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let ip = parts
.extensions
.get::<crate::middleware::ClientIp>()
.map(|c| c.0.clone())
.unwrap_or_else(|| "unknown".to_string());
let user_agent = parts
.headers
.get(axum::http::header::USER_AGENT)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
let started = parts
.extensions
.get::<crate::middleware::RequestStart>()
.map(|r| r.0)
.unwrap_or_else(std::time::Instant::now);
let request_id = parts
.extensions
.get::<crate::middleware::request_id::RequestId>()
.map(|r| r.0.clone());
Ok(Self { ip, user_agent, started, request_id })
}
}
#[derive(Debug, Clone)]
pub struct TenantId(pub i64);
impl std::ops::Deref for TenantId {
type Target = i64;
fn deref(&self) -> &i64 {
&self.0
}
}
impl<S: Send + Sync> FromRequestParts<S> for TenantId {
type Rejection = ApiError;
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
parts
.extensions
.get::<crate::tenant::TenantContext>()
.and_then(|ctx| ctx.tenant_id)
.map(TenantId)
.ok_or_else(|| ApiError::bad_request(error_message_of(ErrorCode::BadRequest)))
}
}
#[derive(Debug, Clone)]
pub struct RequestedTenantId(pub String);
impl std::ops::Deref for RequestedTenantId {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl<S: Send + Sync> FromRequestParts<S> for RequestedTenantId {
type Rejection = ApiError;
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
parts
.headers
.get(crate::tenant::tenant_header())
.and_then(|v| v.to_str().ok())
.filter(|s| !s.is_empty())
.map(|s| RequestedTenantId(s.to_string()))
.ok_or_else(|| ApiError::bad_request(error_message_of(ErrorCode::BadRequest)))
}
}
use axum::body::Body;
use std::path::PathBuf;
#[derive(Debug, Clone)]
pub struct FileSender {
root: PathBuf,
}
impl FileSender {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
pub async fn send(
&self,
path: &str,
content_type: &str,
) -> Result<axum::response::Response, ApiError> {
let root = lexically_canonicalize(&self.root);
let full = lexically_canonicalize(&root.join(path.trim_start_matches('/')));
if !is_within(&full, &root) {
return Err(ApiError::forbidden(error_message_of(ErrorCode::Forbidden)));
}
let file = tokio::fs::File::open(&full)
.await
.map_err(|_| ApiError::not_found(error_message_of(ErrorCode::NotFound)))?;
let len = file
.metadata()
.await
.map_err(|_| ApiError::not_found(error_message_of(ErrorCode::NotFound)))?
.len();
let stream = tokio_util::io::ReaderStream::new(file);
let filename = full
.file_name()
.and_then(|n| n.to_str())
.map(sanitize_header_filename)
.unwrap_or_else(|| "download".to_string());
axum::response::Response::builder()
.header("Content-Type", content_type)
.header("Content-Length", len)
.header(
"Content-Disposition",
format!("attachment; filename=\"{}\"", filename),
)
.body(Body::from_stream(stream))
.map_err(|e| ApiError::internal(format!("构建文件响应失败: {}", e)))
}
}
impl<S: Send + Sync> FromRequestParts<S> for FileSender {
type Rejection = ApiError;
async fn from_request_parts(_parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
let path: PathBuf = { crate::resources::download_path().into() };
Ok(FileSender::new(path))
}
}
fn sanitize_header_filename(name: &str) -> String {
let sanitized: String = name
.chars()
.map(|c| match c {
'"' | '\\' | '\r' | '\n' => '_',
c => c,
})
.collect();
if sanitized.is_empty() || !sanitized.is_ascii() || sanitized.bytes().any(|b| !(0x20..=0x7e).contains(&b)) {
"download".to_string()
} else {
sanitized
}
}
fn lexically_canonicalize(path: &std::path::Path) -> PathBuf {
use std::path::Component;
let mut out: Vec<Component<'_>> = Vec::new();
for comp in path.components() {
match comp {
Component::CurDir => {}
Component::ParentDir => {
if let Some(Component::Normal(_)) = out.last() {
out.pop();
}
}
other => out.push(other),
}
}
out.iter().collect()
}
fn is_within(path: &std::path::Path, base: &std::path::Path) -> bool {
let base_segments: Vec<_> = base.components().collect();
let path_segments: Vec<_> = path.components().collect();
if path_segments.len() < base_segments.len() {
return path == base;
}
path_segments[..base_segments.len()] == base_segments[..]
}