Add validator

This commit is contained in:
Pierre Berthe 2024-07-25 18:19:56 +02:00
parent 67b3a91a23
commit 11ca3e3aae
3 changed files with 191 additions and 19 deletions

View file

@ -17,6 +17,7 @@ use maud::{html, Escaper, Markup, PreEscaped, DOCTYPE};
use serde::{Deserialize, Serialize};
use store::Store;
use tokio::net::TcpListener;
use validator::{Validate, ValidationError};
mod common;
mod store;
@ -146,35 +147,38 @@ async fn topic(Path(name): Path<String>, State(state): State<MainState>) -> impl
)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
struct PostContent {
#[validate(length(min = 1, max = 32), custom(function = "validate_topic"))]
topic: String,
#[validate(length(min = 10, max = 10_000))]
content: String,
#[validate(length(min = 2, max = 32))]
author: String,
}
async fn post(
State(state): State<MainState>,
Form(PostContent {
fn validate_topic(topic: &str) -> Result<(), ValidationError> {
if topic.starts_with('_') || topic.ends_with('_') {
return Err(ValidationError::new("Bad topic format."));
}
Ok(())
}
async fn post(State(state): State<MainState>, Form(post_content): Form<PostContent>) -> Response {
let mut store = state.store.write().unwrap();
let date = Utc::now().format("%d/%m/%Y");
if post_content.validate().is_err() {
return (StatusCode::BAD_REQUEST, "Bad input.").into_response();
}
let PostContent {
topic,
content,
author,
}): Form<PostContent>,
) -> Response {
let mut store = state.store.write().unwrap();
let date = Utc::now().format("%d/%m/%Y");
let topic = sanithize_identifier(topic.trim());
let content = content.trim();
} = post_content;
if content.len() < 10 || content.len() > 10_000 {
return (StatusCode::BAD_REQUEST, "Bad content.").into_response();
}
if author.len() > 2 || author.len() > 32 {
return (StatusCode::BAD_REQUEST, "Bad author.").into_response();
}
if topic.len() > 32 || topic.is_empty() || topic.starts_with('_') || topic.ends_with('_') {
return (StatusCode::BAD_REQUEST, "Bad topic.").into_response();
}
let topic = sanithize_identifier(&topic);
let content = format!("{content}\n\t~{author}, {date}");
store.insert(&topic, content).unwrap();