cot 0.3.1

The Rust web framework for lazy developers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! Forms and form fields for handling user input.
//!
//! This module provides a way to define forms and form fields for handling user
//! input in a web application. It provides a way to create forms from requests,
//! validate the form data, and render the form fields in an HTML form.
//!
//! # `Form` derive macro
//!
//! The easiest way to work with forms in Cot is to use the
//! [`Form`](derive@Form) derive macro. Just define a structure that will hold
//! all the form data you need, and derive the [`Form`] trait for it.
//!
//! ```
//! use cot::form::Form;
//!
//! #[derive(Form)]
//! struct MyForm {
//!     #[form(opt(max_length = 100))]
//!     name: String,
//! }
//! ```

/// Built-in form fields that can be used in a form.
pub mod fields;

use std::borrow::Cow;
use std::fmt::{Debug, Display};

use async_trait::async_trait;
use bytes::Bytes;
/// Derive the [`Form`] trait for a struct and create a [`FormContext`] for it.
///
/// This macro will generate an implementation of the [`Form`] trait for the
/// given named struct. Note that all the fields of the struct **must**
/// implement the [`AsFormField`] trait.
///
/// # Rendering
///
/// In order for the [`FormContext`] to be renderable in templates, all the form
/// fields (i.e. [`AsFormField::Type`]) must implement the [`Display`] and
/// [`askama::filters::HtmlSafe`] traits. If you are implementing your own form
/// field types, you should make sure they implement these traits (and you have
/// to make sure the types are safe to render as HTML, possibly escaping user
/// input if needed).
///
/// Note that even if the form is not rendered in a template, you will still be
/// able to render the fields individually.
///
/// # Safety
///
/// The implementation of [`Display`] for the form context that this derive
/// macro generates depends on the implementation of [`Display`] for the form
/// fields. If the form fields are not safe to render as HTML, the form context
/// will not be safe to render as HTML either.
pub use cot_macros::Form;
use thiserror::Error;

use crate::headers::FORM_CONTENT_TYPE;
use crate::request;
use crate::request::{Request, RequestExt};

/// Error occurred while processing a form.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum FormError {
    /// An error occurred while processing the request, before validating the
    /// form data.
    #[error("Request error: {error}")]
    RequestError {
        /// The error that occurred while processing the request.
        #[from]
        error: Box<crate::Error>,
    },
}

/// The result of validating a form.
///
/// This enum is used to represent the result of validating a form. In the case
/// of a successful validation, the `Ok` variant contains the form object. In
/// the case of a failed validation, the `ValidationError` variant contains the
/// context object with the validation errors, as well as the user's input.
#[must_use]
#[derive(Debug, Clone)]
pub enum FormResult<T: Form> {
    /// The form validation passed.
    Ok(T),
    /// The form validation failed.
    ValidationError(T::Context),
}

impl<T: Form> FormResult<T> {
    /// Unwraps the form result, panicking if the form validation failed.
    ///
    /// This should only be used in tests or in cases where the form validation
    /// is guaranteed to pass.
    ///
    /// # Panics
    ///
    /// Panics if the form validation failed.
    #[track_caller]
    pub fn unwrap(self) -> T {
        match self {
            Self::Ok(form) => form,
            Self::ValidationError(context) => panic!("Form validation failed: {context:?}"),
        }
    }
}

/// An error that can occur when validating a form field.
#[derive(Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
#[error("{message}")]
pub enum FormFieldValidationError {
    /// The field is required.
    #[error("This field is required.")]
    Required,
    /// The field value is too long.
    #[error("This exceeds the maximum length of {max_length}.")]
    MaximumLengthExceeded {
        /// The maximum length of the field.
        max_length: u32,
    },

    /// The field value is too short.
    #[error("This is below the minimum length of {min_length}.")]
    MinimumLengthNotMet {
        /// The minimum length of the field.
        min_length: u32,
    },

    /// The field value is below the permitted minimum.
    #[error("This is below the minimum value of {min_value}.")]
    MinimumValueNotMet {
        /// The minimum permitted value.
        min_value: String,
    },

    /// The field value exceeds the permitted maximum.
    #[error("This exceeds the maximum value of {max_value}.")]
    MaximumValueExceeded {
        /// The maximum permitted value.
        max_value: String,
    },

    /// The field value is required to be true.
    #[error("This field must be checked.")]
    BooleanRequiredToBeTrue,
    /// The field value is invalid.
    #[error("Value is not valid for this field.")]
    InvalidValue(String),
    /// Custom error with given message.
    #[error("{0}")]
    Custom(Cow<'static, str>),
}

impl FormFieldValidationError {
    /// Creates a new `FormFieldValidationError` for an invalid value of a
    /// field.
    #[must_use]
    pub fn invalid_value<T: Into<String>>(value: T) -> Self {
        Self::InvalidValue(value.into())
    }

    /// Creates a new `FormFieldValidationError` for a field value that is too
    /// long.
    #[must_use]
    pub fn maximum_length_exceeded(max_length: u32) -> Self {
        Self::MaximumLengthExceeded { max_length }
    }

    /// Creates a new `FormFieldValidationError` for a field value that is too
    /// short.
    #[must_use]
    pub fn minimum_length_not_met(min_length: u32) -> Self {
        FormFieldValidationError::MinimumLengthNotMet { min_length }
    }

    /// Creates a new `FormFieldValidatorError`for a field value below the
    /// permitted minimum value.
    #[must_use]
    pub fn minimum_value_not_met<T: Display>(min_value: T) -> Self {
        FormFieldValidationError::MinimumValueNotMet {
            min_value: min_value.to_string(),
        }
    }

    /// Creates a new `FormFieldValidationError` for a field value that exceeds
    /// the permitted maximum value
    #[must_use]
    pub fn maximum_value_exceeded<T: Display>(max_value: T) -> Self {
        FormFieldValidationError::MaximumValueExceeded {
            max_value: max_value.to_string(),
        }
    }

    /// Creates a new `FormFieldValidationError` from a `String`.
    #[must_use]
    pub const fn from_string(message: String) -> Self {
        Self::Custom(Cow::Owned(message))
    }

    /// Creates a new `FormFieldValidationError` from a static string.
    #[must_use]
    pub const fn from_static(message: &'static str) -> Self {
        Self::Custom(Cow::Borrowed(message))
    }
}

impl From<email_address::Error> for FormFieldValidationError {
    fn from(error: email_address::Error) -> Self {
        FormFieldValidationError::from_string(error.to_string())
    }
}

/// An enum indicating the target of a form validation error.
#[derive(Debug)]
pub enum FormErrorTarget<'a> {
    /// An error targeting a single field.
    Field(&'a str),
    /// An error targeting the entire form.
    Form,
}

/// A trait for types that can be used as forms.
///
/// This trait is used to define a type that can be used as a form. It provides
/// a way to create a form from a request, build a context from the request, and
/// validate the form.
///
/// # Deriving
///
/// This trait can, and should be derived using the [`Form`](derive@Form) derive
/// macro. This macro generates the implementation of the trait for the type,
/// including the implementation of the [`FormContext`] trait for the context
/// type.
///
/// ```
/// use cot::form::Form;
///
/// #[derive(Form)]
/// struct MyForm {
///     #[form(opt(max_length = 100))]
///     name: String,
/// }
/// ```
#[async_trait]
#[diagnostic::on_unimplemented(
    message = "`{Self}` does not implement the `Form` trait",
    label = "`{Self}` is not a form",
    note = "add #[derive(cot::form::Form)] to the struct to automatically derive the trait"
)]
pub trait Form: Sized {
    /// The context type associated with the form.
    type Context: FormContext;

    /// Creates a form struct from a request.
    ///
    /// # Errors
    ///
    /// This method should return an error if the form data could not be read
    /// from the request.
    async fn from_request(request: &mut Request) -> Result<FormResult<Self>, FormError>;

    /// Creates the context for the form from `self`.
    ///
    /// This is useful for pre-populating forms with objects created in the code
    /// or obtained externally, such as from a database.
    fn to_context(&self) -> Self::Context;

    /// Builds the context for the form from a request.
    ///
    /// Note that this doesn't try to convert the values from the form fields
    /// into the final types, so this context object may not include all the
    /// errors. The conversion is done in the [`Self::from_request`] method.
    ///
    /// # Errors
    ///
    /// This method should return an error if the form data could not be read
    /// from the request.
    async fn build_context(request: &mut Request) -> Result<Self::Context, FormError> {
        let form_data = form_data(request)
            .await
            .map_err(|error| FormError::RequestError {
                error: Box::new(error),
            })?;

        let mut context = Self::Context::new();

        for (field_id, value) in request::query_pairs(&form_data) {
            let field_id = field_id.as_ref();

            if let Err(err) = context.set_value(field_id, value) {
                context.add_error(FormErrorTarget::Field(field_id), err);
            }
        }

        Ok(context)
    }
}

/// Get the request body as bytes. If the request method is GET or HEAD, the
/// query string is returned. Otherwise, if the request content type is
/// `application/x-www-form-urlencoded`, then the body is read and returned.
/// Otherwise, an error is thrown.
///
/// # Errors
///
/// Throws an error if the request method is not GET or HEAD and the content
/// type is not `application/x-www-form-urlencoded`.
/// Throws an error if the request body could not be read.
pub async fn form_data(request: &mut Request) -> crate::Result<Bytes> {
    if request.method() == http::Method::GET || request.method() == http::Method::HEAD {
        if let Some(query) = request.uri().query() {
            return Ok(Bytes::copy_from_slice(query.as_bytes()));
        }

        Ok(Bytes::new())
    } else {
        request.expect_content_type(FORM_CONTENT_TYPE)?;

        let body = std::mem::take(request.body_mut());
        let bytes = body.into_bytes().await?;

        Ok(bytes)
    }
}

/// A trait for form contexts.
///
/// A form context is used to store the state of a form, such as the values of
/// the fields and any errors that occur during validation. This trait is used
/// to define the interface for a form context, which is used to interact with
/// the form fields and errors.
///
/// This trait is typically not implemented directly; instead, its
/// implementations are generated automatically through the
/// [`Form`](derive@Form) derive macro.
pub trait FormContext: Debug {
    /// Creates a new form context without any initial form data.
    fn new() -> Self
    where
        Self: Sized;

    /// Returns an iterator over the fields in the form.
    fn fields(&self) -> Box<dyn DoubleEndedIterator<Item = &dyn DynFormField> + '_>;

    /// Sets the value of a form field.
    ///
    /// # Errors
    ///
    /// This method should return an error if the value is invalid.
    fn set_value(
        &mut self,
        field_id: &str,
        value: Cow<'_, str>,
    ) -> Result<(), FormFieldValidationError>;

    /// Adds a validation error to the form context.
    fn add_error(&mut self, target: FormErrorTarget<'_>, error: FormFieldValidationError) {
        self.errors_for_mut(target).push(error);
    }

    /// Returns the validation errors for a target in the form context.
    fn errors_for(&self, target: FormErrorTarget<'_>) -> &[FormFieldValidationError];

    /// Returns a mutable reference to the validation errors for a target in the
    /// form context.
    fn errors_for_mut(&mut self, target: FormErrorTarget<'_>)
    -> &mut Vec<FormFieldValidationError>;

    /// Returns whether the form context has any validation errors.
    fn has_errors(&self) -> bool;
}

/// Generic options valid for all types of form fields.
#[derive(Debug)]
pub struct FormFieldOptions {
    /// The HTML ID of the form field.
    pub id: String,
    /// Display name of the form field.
    pub name: String,
    /// Whether the field is required. Note that this really only adds
    /// "required" field to the HTML input element, since by default all
    /// fields are required. If you want to make a field optional, just use
    /// [`Option`] in the struct definition.
    pub required: bool,
}

/// A form field.
///
/// This trait is used to define a type of field that can be used in a form. It
/// is used to render the field in an HTML form, set the value of the field, and
/// validate it. Typically, the implementors of this trait are used indirectly
/// through the [`Form`] trait and field types that implement [`AsFormField`].
pub trait FormField: Display {
    /// Custom options for the form field, unique for each field type.
    type CustomOptions: Default;

    /// Creates a new form field with the given options.
    fn with_options(options: FormFieldOptions, custom_options: Self::CustomOptions) -> Self
    where
        Self: Sized;

    /// Returns the generic options for the form field.
    fn options(&self) -> &FormFieldOptions;

    /// Returns the ID of the form field.
    fn id(&self) -> &str {
        &self.options().id
    }

    /// Returns the display name of the form field.
    fn name(&self) -> &str {
        &self.options().name
    }

    /// Returns the string value of the form field.
    fn value(&self) -> Option<&str>;

    /// Sets the string value of the form field.
    ///
    /// This method should convert the value to the appropriate type for the
    /// field, such as a number for a number field.
    fn set_value(&mut self, value: Cow<'_, str>);
}

/// A version of [`FormField`] that can be used in a dynamic context.
///
/// This trait is used to allow a form field to be used in a dynamic context,
/// such as when using Form field iterator. It provides access to the field's
/// options, value, and rendering, among others.
///
/// This trait is implemented for all types that implement [`FormField`].
pub trait DynFormField: Display {
    /// Returns the generic options for the form field.
    fn dyn_options(&self) -> &FormFieldOptions;

    /// Returns the HTML ID of the form field.
    fn dyn_id(&self) -> &str;

    /// Returns the string value of the form field.
    fn dyn_value(&self) -> Option<&str>;

    /// Sets the string value of the form field.
    fn dyn_set_value(&mut self, value: Cow<'_, str>);
}

impl<T: FormField> DynFormField for T {
    fn dyn_options(&self) -> &FormFieldOptions {
        FormField::options(self)
    }

    fn dyn_id(&self) -> &str {
        FormField::id(self)
    }

    fn dyn_value(&self) -> Option<&str> {
        FormField::value(self)
    }

    fn dyn_set_value(&mut self, value: Cow<'_, str>) {
        FormField::set_value(self, value);
    }
}

/// A trait for types that can be used as form fields.
///
/// This trait uses [`FormField`] to define a type that can be used as a form
/// field. It provides a way to clean the value of the field, which is used to
/// validate the field's value before converting to the final type.
pub trait AsFormField {
    /// The form field type associated with the field.
    type Type: FormField;

    /// Creates a new form field with the given options and custom options.
    ///
    /// This method is used to create a new instance of the form field with the
    /// given options and custom options. The options are used to set the
    /// properties of the field, such as the ID and whether the field is
    /// required.
    ///
    /// The custom options are unique to each field type and are used to set
    /// additional properties of the field.
    fn new_field(
        options: FormFieldOptions,
        custom_options: <Self::Type as FormField>::CustomOptions,
    ) -> Self::Type {
        Self::Type::with_options(options, custom_options)
    }

    /// Validates the value of the field and converts it to the final type. This
    /// method should return an error if the value is invalid.
    ///
    /// # Errors
    ///
    /// Returns an error if the value fails to validate or convert to the final
    /// type
    fn clean_value(field: &Self::Type) -> Result<Self, FormFieldValidationError>
    where
        Self: Sized;

    /// Returns `self` as a value that can be set with [`FormField::set_value`].
    fn to_field_value(&self) -> String;
}

#[cfg(test)]
mod tests {
    use bytes::Bytes;

    use crate::Body;
    use crate::form::form_data;
    use crate::headers::FORM_CONTENT_TYPE;

    #[cot::test]
    async fn form_data_extract_get_empty() {
        let mut request = http::Request::builder()
            .method(http::Method::GET)
            .uri("https://example.com")
            .body(Body::empty())
            .unwrap();

        let bytes = form_data(&mut request).await.unwrap();
        assert_eq!(bytes, Bytes::from_static(b""));
    }

    #[cot::test]
    async fn form_data_extract_get() {
        let mut request = http::Request::builder()
            .method(http::Method::GET)
            .uri("https://example.com/?hello=world")
            .body(Body::empty())
            .unwrap();

        let bytes = form_data(&mut request).await.unwrap();
        assert_eq!(bytes, Bytes::from_static(b"hello=world"));
    }

    #[cot::test]
    async fn form_data_extract() {
        let mut request = http::Request::builder()
            .method(http::Method::POST)
            .header(http::header::CONTENT_TYPE, FORM_CONTENT_TYPE)
            .body(Body::fixed("hello=world"))
            .unwrap();

        let bytes = form_data(&mut request).await.unwrap();
        assert_eq!(bytes, Bytes::from_static(b"hello=world"));
    }
}