2 schema::captcha_answer::dsl::{answer, captcha_answer, uuid},
3 source::captcha_answer::{CaptchaAnswer, CaptchaAnswerForm, CheckCaptchaAnswer},
4 utils::{functions::lower, get_conn, DbPool},
15 use diesel_async::RunQueryDsl;
18 pub async fn insert(pool: &mut DbPool<'_>, captcha: &CaptchaAnswerForm) -> Result<Self, Error> {
19 let conn = &mut get_conn(pool).await?;
21 insert_into(captcha_answer)
23 .get_result::<Self>(conn)
27 pub async fn check_captcha(
28 pool: &mut DbPool<'_>,
29 to_check: CheckCaptchaAnswer,
30 ) -> Result<bool, Error> {
31 let conn = &mut get_conn(pool).await?;
33 // fetch requested captcha
34 let captcha_exists = select(exists(
36 .filter((uuid).eq(to_check.uuid))
37 .filter(lower(answer).eq(to_check.answer.to_lowercase().clone())),
39 .get_result::<bool>(conn)
42 // delete checked captcha
43 delete(captcha_answer.filter(uuid.eq(to_check.uuid)))
53 #![allow(clippy::unwrap_used)]
54 #![allow(clippy::indexing_slicing)]
57 source::captcha_answer::{CaptchaAnswer, CaptchaAnswerForm, CheckCaptchaAnswer},
58 utils::build_db_pool_for_tests,
60 use serial_test::serial;
64 async fn test_captcha_happy_path() {
65 let pool = &build_db_pool_for_tests().await;
66 let pool = &mut pool.into();
68 let inserted = CaptchaAnswer::insert(
71 answer: "XYZ".to_string(),
75 .expect("should not fail to insert captcha");
77 let result = CaptchaAnswer::check_captcha(
81 answer: "xyz".to_string(),
86 assert!(result.is_ok());
87 assert!(result.unwrap());
92 async fn test_captcha_repeat_answer_fails() {
93 let pool = &build_db_pool_for_tests().await;
94 let pool = &mut pool.into();
96 let inserted = CaptchaAnswer::insert(
99 answer: "XYZ".to_string(),
103 .expect("should not fail to insert captcha");
105 let _result = CaptchaAnswer::check_captcha(
109 answer: "xyz".to_string(),
114 let result_repeat = CaptchaAnswer::check_captcha(
118 answer: "xyz".to_string(),
123 assert!(result_repeat.is_ok());
124 assert!(!result_repeat.unwrap());