ctb_io_webui/
flexible_form.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Axum extractor that can handle both `application/x-www-form-urlencoded` and
21//! `multipart/form-data` content types, using `axum::Form` and
22//! `axum_typed_multipart::TypedMultipart` internally.
23//!
24//! It will only work for forms that do not have file uploads, as those are
25//! represented as Bytes objects which can't be deserialized. For those, just
26//! use `TypedMultipart`.
27
28use axum::extract::{FromRequest, Request};
29use axum_extra::extract::{Form, FormRejection};
30use axum_typed_multipart::{
31    TryFromMultipartWithState, TypedMultipart, TypedMultipartError,
32};
33
34pub struct FlexibleForm<T>(pub T);
35
36/// Custom rejection for unsupported content types.
37#[derive(Debug)]
38pub struct UnsupportedContentTypeRejection {
39    pub error: String,
40}
41
42// Custom rejection type to handle both errors
43#[derive(Debug)]
44pub enum FlexibleFormRejection {
45    Multipart(TypedMultipartError),
46    Form(FormRejection),
47    UnsupportedContentType(UnsupportedContentTypeRejection),
48}
49
50impl<T, S> FromRequest<S> for FlexibleForm<T>
51where
52    T: TryFromMultipartWithState<S> + serde::de::DeserializeOwned,
53    S: Send + Sync,
54{
55    type Rejection = FlexibleFormRejection;
56
57    /// Attempts to extract the form data first as a Form, then as `TypedMultipart`.
58    async fn from_request(
59        req: Request,
60        state: &S,
61    ) -> Result<Self, Self::Rejection> {
62        let content_type = req
63            .headers()
64            .get(axum::http::header::CONTENT_TYPE)
65            .and_then(|v| v.to_str().ok())
66            // Reason for fallback: request missing Content-Type header defaults to empty content type string
67            .unwrap_or("");
68
69        match content_type {
70            ct if ct.starts_with("application/x-www-form-urlencoded") => {
71                // Try as form
72                match Form::<T>::from_request(req, state).await {
73                    Ok(Form(data)) => Ok(FlexibleForm(data)),
74                    Err(form_err) => Err(FlexibleFormRejection::Form(form_err)),
75                }
76            }
77            ct if ct.starts_with("multipart/form-data") => {
78                // Try as multipart
79                match TypedMultipart::<T>::from_request(req, state).await {
80                    Ok(TypedMultipart(data)) => Ok(FlexibleForm(data)),
81                    Err(multipart_err) => {
82                        Err(FlexibleFormRejection::Multipart(multipart_err))
83                    }
84                }
85            }
86            &_ => Err(FlexibleFormRejection::UnsupportedContentType(
87                UnsupportedContentTypeRejection {
88                    error: "Unsupported content type".into(),
89                },
90            )),
91        }
92    }
93}
94
95// Implement IntoResponse for the rejection if needed (for error handling)
96impl axum::response::IntoResponse for FlexibleFormRejection {
97    fn into_response(self) -> axum::response::Response {
98        match self {
99            FlexibleFormRejection::Multipart(e) => e.into_response(),
100            FlexibleFormRejection::Form(e) => e.into_response(),
101            FlexibleFormRejection::UnsupportedContentType(e) => {
102                use axum::http::StatusCode;
103                (StatusCode::UNSUPPORTED_MEDIA_TYPE, e.error).into_response()
104            }
105        }
106    }
107}