diff options
Diffstat (limited to 'comments/src/main.rs')
-rw-r--r-- | comments/src/main.rs | 35 |
1 files changed, 27 insertions, 8 deletions
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<UrlQuery>, + State(ctx): State<Ctx>, + Query(uq): Query<UrlQuery> ) -> Result<String, (StatusCode, String)> { - 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<UrlQuery>, - State(ctx): State<Ctx>) -> Result<String, (StatusCode,String)> { + State(ctx): State<Ctx>, + Query(uq): Query<UrlQuery>) -> Result<String, (StatusCode,String)> { 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<Ctx>, Form(post_comment): Form<PostComment>) -> Result<Redirect,(StatusCode,String)> { + 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 |