1use std::collections::HashMap;
4use std::sync::Arc;
5
6use serenade_http::{Method, Request};
7use serenade_security::{CSRF_FIELD_NAME, CsrfToken, CsrfTokenManager, SecurityError};
8use serenade_validator::{Constraint, ConstraintViolationList, RecursiveValidator, Validator};
9
10use crate::collection::collection_field_name;
11use crate::file::UploadedFile;
12use crate::kind::{FieldConfig, FieldKind, FileOptions};
13use crate::multipart::parse_form_body;
14use crate::render::RenderedForm;
15use crate::theme::{form_csrf, form_row};
16use crate::transformer::{DataTransformer, join_multi};
17use crate::{FormError, escape_attr};
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum FormStatus {
22 NotSubmitted,
24 Bound,
26}
27
28pub struct Field {
30 name: String,
31 pub(crate) value: String,
32 constraints: Vec<Arc<dyn Constraint>>,
33 config: FieldConfig,
34 pub(crate) transformer: Option<Arc<dyn DataTransformer>>,
35}
36
37impl Field {
38 fn new(
39 name: impl Into<String>,
40 config: FieldConfig,
41 constraints: Vec<Arc<dyn Constraint>>,
42 transformer: Option<Arc<dyn DataTransformer>>,
43 ) -> Self {
44 Self {
45 name: name.into(),
46 value: String::new(),
47 constraints,
48 config,
49 transformer,
50 }
51 }
52
53 #[must_use]
55 pub fn name(&self) -> &str {
56 &self.name
57 }
58
59 #[must_use]
61 pub fn value(&self) -> &str {
62 &self.value
63 }
64
65 #[must_use]
67 pub const fn kind(&self) -> FieldKind {
68 self.config.kind()
69 }
70
71 #[must_use]
73 pub const fn config(&self) -> &FieldConfig {
74 &self.config
75 }
76}
77
78pub struct Form {
80 name: String,
81 method: Method,
82 action: String,
83 fields: Vec<Field>,
84 csrf_enabled: bool,
85 csrf_token: Option<CsrfToken>,
86 submitted: bool,
87 violations: ConstraintViolationList,
88 files: HashMap<String, UploadedFile>,
89}
90
91impl Form {
92 #[must_use]
94 pub fn builder(name: impl Into<String>) -> FormBuilder {
95 FormBuilder::new(name)
96 }
97
98 #[must_use]
100 pub fn name(&self) -> &str {
101 &self.name
102 }
103
104 #[must_use]
106 pub const fn is_submitted(&self) -> bool {
107 self.submitted
108 }
109
110 #[must_use]
112 pub fn data(&self) -> HashMap<String, String> {
113 self.fields
114 .iter()
115 .map(|f| (f.name.clone(), f.value.clone()))
116 .collect()
117 }
118
119 #[must_use]
121 pub fn fields(&self) -> &[Field] {
122 &self.fields
123 }
124
125 #[must_use]
127 pub fn get(&self, name: &str) -> Option<&str> {
128 self.fields
129 .iter()
130 .find(|f| f.name == name)
131 .map(Field::value)
132 }
133
134 #[must_use]
136 pub fn file(&self, name: &str) -> Option<&UploadedFile> {
137 self.files.get(name)
138 }
139
140 pub fn take_file(&mut self, name: &str) -> Option<UploadedFile> {
142 self.files.remove(name)
143 }
144
145 pub fn set(&mut self, name: &str, value: impl Into<String>) -> bool {
149 if let Some(field) = self.fields.iter_mut().find(|f| f.name == name) {
150 field.value = value.into();
151 true
152 } else {
153 false
154 }
155 }
156
157 #[must_use]
159 pub const fn violations(&self) -> &ConstraintViolationList {
160 &self.violations
161 }
162
163 #[must_use]
165 pub const fn csrf_enabled(&self) -> bool {
166 self.csrf_enabled
167 }
168
169 pub fn prepare_csrf(&mut self, manager: &dyn CsrfTokenManager) -> Result<(), FormError> {
175 if !self.csrf_enabled {
176 return Ok(());
177 }
178 self.csrf_token = Some(manager.get_token(&self.name)?);
179 Ok(())
180 }
181
182 pub fn handle_request(
192 &mut self,
193 request: &Request,
194 manager: &dyn CsrfTokenManager,
195 ) -> Result<FormStatus, FormError> {
196 self.submitted = false;
197 self.violations = ConstraintViolationList::new();
198 self.files.clear();
199 if !matches!(request.method(), Method::Post | Method::Put | Method::Patch) {
200 return Ok(FormStatus::NotSubmitted);
201 }
202 let file_options = self.file_options_map();
203 let parsed = parse_form_body(
204 request.headers().get("content-type"),
205 request.body(),
206 &file_options,
207 )?;
208 if self.csrf_enabled {
209 let submitted = parsed
210 .fields
211 .get(CSRF_FIELD_NAME)
212 .and_then(|v| v.last())
213 .map_or("", String::as_str);
214 let token = CsrfToken::new(&self.name, submitted);
215 if !manager.is_token_valid(&token) {
216 return Err(SecurityError::InvalidCsrfToken.into());
217 }
218 self.csrf_token = Some(token);
219 }
220 for field in &mut self.fields {
221 if matches!(field.config(), FieldConfig::File(_)) {
222 if let Some(upload) = parsed.files.get(field.name()) {
223 field.value = upload.filename().unwrap_or("").to_owned();
224 } else {
225 field.value.clear();
226 }
227 } else {
228 bind_field(field, &parsed.fields)?;
229 }
230 }
231 self.files = parsed.files;
232 self.submitted = true;
233 Ok(FormStatus::Bound)
234 }
235
236 pub fn validate(&mut self, validator: &dyn Validator) -> bool {
238 let mut violations = ConstraintViolationList::new();
239 for field in &self.fields {
240 if matches!(field.config(), FieldConfig::File(_)) {
241 continue;
242 }
243 let refs: Vec<&dyn Constraint> = field.constraints.iter().map(AsRef::as_ref).collect();
244 let field_violations = validator.validate_value(&field.value, &field.name, &refs);
245 for v in field_violations.as_slice() {
246 violations.add(v.clone());
247 }
248 }
249 let ok = violations.is_empty();
250 self.violations = violations;
251 ok
252 }
253
254 #[must_use]
256 pub fn is_valid(&mut self) -> bool {
257 self.validate(&RecursiveValidator::new())
258 }
259
260 pub fn render(&self) -> Result<RenderedForm, FormError> {
269 let csrf_html = form_csrf(self)?;
270 let mut fields_html = String::new();
271 for field in &self.fields {
272 fields_html.push_str(&form_row(field, &self.violations)?);
273 }
274 let enctype = if self.has_file_field() {
275 r#" enctype="multipart/form-data""#
276 } else {
277 ""
278 };
279 let html = format!(
280 r#"<form name="{name}" method="{method}" action="{action}"{enctype}>{csrf}{fields}</form>"#,
281 name = escape_attr(&self.name),
282 method = escape_attr(self.method.as_str()),
283 action = escape_attr(&self.action),
284 csrf = csrf_html,
285 fields = fields_html,
286 );
287 Ok(RenderedForm { html })
288 }
289
290 pub fn csrf_html(&self) -> Result<String, FormError> {
296 if !self.csrf_enabled {
297 return Ok(String::new());
298 }
299 let token = self
300 .csrf_token
301 .as_ref()
302 .ok_or(SecurityError::InvalidCsrfToken)?;
303 Ok(format!(
304 r#"<input type="hidden" name="{}" value="{}" />"#,
305 escape_attr(CSRF_FIELD_NAME),
306 escape_attr(token.value())
307 ))
308 }
309
310 fn has_file_field(&self) -> bool {
311 self.fields
312 .iter()
313 .any(|field| matches!(field.config(), FieldConfig::File(_)))
314 }
315
316 fn file_options_map(&self) -> HashMap<String, FileOptions> {
317 self.fields
318 .iter()
319 .filter_map(|field| {
320 field
321 .config()
322 .as_file()
323 .map(|options| (field.name().to_owned(), options.clone()))
324 })
325 .collect()
326 }
327}
328
329fn bind_field(field: &mut Field, values: &HashMap<String, Vec<String>>) -> Result<(), FormError> {
330 let view = match field.config() {
331 FieldConfig::Choice(options) if options.multiple => {
332 let submitted = values.get(field.name()).cloned().unwrap_or_default();
333 join_multi(&submitted)
334 }
335 FieldConfig::Checkbox(_) => values
336 .get(field.name())
337 .and_then(|v| v.last())
338 .cloned()
339 .unwrap_or_default(),
340 _ => values
341 .get(field.name())
342 .and_then(|v| v.last())
343 .cloned()
344 .unwrap_or_default(),
345 };
346 field.value = if let Some(transformer) = &field.transformer {
347 transformer.reverse_transform(&view)?
348 } else {
349 view
350 };
351 Ok(())
352}
353
354pub struct FormBuilder {
356 name: String,
357 method: Method,
358 action: String,
359 fields: Vec<Field>,
360 csrf_enabled: bool,
361}
362
363impl FormBuilder {
364 fn new(name: impl Into<String>) -> Self {
365 Self {
366 name: name.into(),
367 method: Method::Post,
368 action: String::new(),
369 fields: Vec::new(),
370 csrf_enabled: true,
371 }
372 }
373
374 #[must_use]
376 pub const fn method(mut self, method: Method) -> Self {
377 self.method = method;
378 self
379 }
380
381 #[must_use]
383 pub fn action(mut self, action: impl Into<String>) -> Self {
384 self.action = action.into();
385 self
386 }
387
388 #[must_use]
390 pub const fn csrf(mut self, enabled: bool) -> Self {
391 self.csrf_enabled = enabled;
392 self
393 }
394
395 #[must_use]
397 pub fn field(self, name: impl Into<String>, constraints: Vec<Arc<dyn Constraint>>) -> Self {
398 self.field_config(name, FieldConfig::default(), constraints)
399 }
400
401 #[must_use]
403 pub fn field_config(
404 mut self,
405 name: impl Into<String>,
406 config: FieldConfig,
407 constraints: Vec<Arc<dyn Constraint>>,
408 ) -> Self {
409 self.fields
410 .push(Field::new(name, config, constraints, None));
411 self
412 }
413
414 #[must_use]
416 pub fn field_transformed(
417 mut self,
418 name: impl Into<String>,
419 config: FieldConfig,
420 constraints: Vec<Arc<dyn Constraint>>,
421 transformer: Arc<dyn DataTransformer>,
422 ) -> Self {
423 self.fields
424 .push(Field::new(name, config, constraints, Some(transformer)));
425 self
426 }
427
428 #[must_use]
442 pub fn compound(
443 mut self,
444 name: impl Into<String>,
445 configure: impl FnOnce(CompoundBuilder) -> CompoundBuilder,
446 ) -> Self {
447 let nested = configure(CompoundBuilder::new(name));
448 self.fields.extend(nested.fields);
449 self
450 }
451
452 #[must_use]
467 pub fn collection(
468 mut self,
469 name: impl Into<String>,
470 count: usize,
471 configure: impl FnOnce(CollectionEntryBuilder) -> CollectionEntryBuilder,
472 ) -> Self {
473 let collection = name.into();
474 let entry = configure(CollectionEntryBuilder::new());
475 for index in 0..count {
476 for spec in &entry.specs {
477 let full_name = collection_field_name(&collection, &index.to_string(), &spec.name);
478 self.fields.push(Field::new(
479 full_name,
480 spec.config.clone(),
481 spec.constraints.clone(),
482 spec.transformer.clone(),
483 ));
484 }
485 }
486 self
487 }
488
489 #[must_use]
491 pub fn build(self) -> Form {
492 Form {
493 name: self.name,
494 method: self.method,
495 action: self.action,
496 fields: self.fields,
497 csrf_enabled: self.csrf_enabled,
498 csrf_token: None,
499 submitted: false,
500 violations: ConstraintViolationList::new(),
501 files: HashMap::new(),
502 }
503 }
504}
505
506pub struct CompoundBuilder {
508 prefix: String,
509 fields: Vec<Field>,
510}
511
512impl CompoundBuilder {
513 fn new(prefix: impl Into<String>) -> Self {
514 Self {
515 prefix: prefix.into(),
516 fields: Vec::new(),
517 }
518 }
519
520 fn child_name(&self, name: impl Into<String>) -> String {
521 format!("{}.{}", self.prefix, name.into())
522 }
523
524 #[must_use]
526 pub fn field(self, name: impl Into<String>, constraints: Vec<Arc<dyn Constraint>>) -> Self {
527 self.field_config(name, FieldConfig::default(), constraints)
528 }
529
530 #[must_use]
532 pub fn field_config(
533 mut self,
534 name: impl Into<String>,
535 config: FieldConfig,
536 constraints: Vec<Arc<dyn Constraint>>,
537 ) -> Self {
538 let full = self.child_name(name);
539 self.fields
540 .push(Field::new(full, config, constraints, None));
541 self
542 }
543
544 #[must_use]
546 pub fn field_transformed(
547 mut self,
548 name: impl Into<String>,
549 config: FieldConfig,
550 constraints: Vec<Arc<dyn Constraint>>,
551 transformer: Arc<dyn DataTransformer>,
552 ) -> Self {
553 let full = self.child_name(name);
554 self.fields
555 .push(Field::new(full, config, constraints, Some(transformer)));
556 self
557 }
558
559 #[must_use]
561 pub fn compound(
562 mut self,
563 name: impl Into<String>,
564 configure: impl FnOnce(Self) -> Self,
565 ) -> Self {
566 let nested = configure(Self::new(self.child_name(name)));
567 self.fields.extend(nested.fields);
568 self
569 }
570}
571
572struct EntryFieldSpec {
573 name: String,
574 config: FieldConfig,
575 constraints: Vec<Arc<dyn Constraint>>,
576 transformer: Option<Arc<dyn DataTransformer>>,
577}
578
579pub struct CollectionEntryBuilder {
581 specs: Vec<EntryFieldSpec>,
582}
583
584impl CollectionEntryBuilder {
585 const fn new() -> Self {
586 Self { specs: Vec::new() }
587 }
588
589 #[must_use]
591 pub fn field(self, name: impl Into<String>, constraints: Vec<Arc<dyn Constraint>>) -> Self {
592 self.field_config(name, FieldConfig::default(), constraints)
593 }
594
595 #[must_use]
597 pub fn field_config(
598 mut self,
599 name: impl Into<String>,
600 config: FieldConfig,
601 constraints: Vec<Arc<dyn Constraint>>,
602 ) -> Self {
603 self.specs.push(EntryFieldSpec {
604 name: name.into(),
605 config,
606 constraints,
607 transformer: None,
608 });
609 self
610 }
611
612 #[must_use]
614 pub fn field_transformed(
615 mut self,
616 name: impl Into<String>,
617 config: FieldConfig,
618 constraints: Vec<Arc<dyn Constraint>>,
619 transformer: Arc<dyn DataTransformer>,
620 ) -> Self {
621 self.specs.push(EntryFieldSpec {
622 name: name.into(),
623 config,
624 constraints,
625 transformer: Some(transformer),
626 });
627 self
628 }
629}