From 30927637f2ae8af9224eb6daeca25793a0675bca Mon Sep 17 00:00:00 2001 From: Martin Ashby Date: Thu, 29 Dec 2022 22:49:33 +0000 Subject: More work on comments --- comments/src/main.rs | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) (limited to 'comments/src/main.rs') diff --git a/comments/src/main.rs b/comments/src/main.rs index 312dafa..287b89e 100644 --- a/comments/src/main.rs +++ b/comments/src/main.rs @@ -14,12 +14,14 @@ use axum::{ http::StatusCode, routing::get, Router, - debug_handler, }; use serde::Deserialize; use sqlx::{ postgres::{PgPool, PgPoolOptions}, - types::time::OffsetDateTime, + types::{ + time::OffsetDateTime, + uuid::Uuid, + }, }; use std::{net::SocketAddr, time::Duration}; @@ -76,13 +78,20 @@ struct UrlQuery { #[derive(Template)] #[template(path = "form.html")] struct CommentForm { - url: String + url: String, + capcha_question: String, + capcha_id: Uuid, } async fn get_form( - Query(uq): Query, + State(ctx): State, + Query(uq): Query ) -> Result { - let c = CommentForm{url: uq.url}; + let capcha = sqlx::query!("select id, question from capchas order by random() limit 1") + .fetch_one(&ctx.pool) + .await + .map_err(internal_error)?; + let c = CommentForm{url: uq.url, capcha_question: capcha.question, capcha_id: capcha.id}; let res = c.render().map_err(internal_error)?; Ok(res) } @@ -99,8 +108,8 @@ struct Comment { } async fn get_comments( - Query(uq): Query, - State(ctx): State) -> Result { + State(ctx): State, + Query(uq): Query) -> Result { let comments = sqlx::query!("select author,comment,ts from comments where url = $1", uq.url) .fetch_all(&ctx.pool) .await @@ -122,12 +131,22 @@ struct PostComment { url: String, author: String, comment: String, + capcha_id: String, + capcha_answer: String, } -#[debug_handler] async fn post_comments( State(ctx): State, Form(post_comment): Form) -> Result { + let capcha_id: Uuid = post_comment.capcha_id.parse() + .map_err(|_| {(StatusCode::BAD_REQUEST, "Invalid capcha_id".to_string())})?; + let ans: String = sqlx::query_as!("select answer from capchas where id = $1", capcha_id) + .fetch_one(&ctx.pool) + .await + .map_err(internal_error)?; + if post_comment.capcha_answer != ans { + return Err((StatusCode::BAD_REQUEST, "Capcha was wrong!".to_string())); + } sqlx::query!("insert into comments(url,author,comment) values($1, $2, $3)", post_comment.url, post_comment.author, post_comment.comment) .execute(&ctx.pool) .await -- cgit v1.2.3-ZIG