mirror of https://github.com/LemmyNet/lemmy
feat: re-added captcha checks (#3289)
parent
76a4513774
commit
2aef6a5a33
@ -0,0 +1,50 @@
|
||||
use crate::{captcha_as_wav_base64, Perform};
|
||||
use actix_web::web::Data;
|
||||
use captcha::{gen, Difficulty};
|
||||
use lemmy_api_common::{
|
||||
context::LemmyContext,
|
||||
person::{CaptchaResponse, GetCaptcha, GetCaptchaResponse},
|
||||
};
|
||||
use lemmy_db_schema::source::{
|
||||
captcha_answer::{CaptchaAnswer, CaptchaAnswerForm},
|
||||
local_site::LocalSite,
|
||||
};
|
||||
use lemmy_utils::error::LemmyError;
|
||||
|
||||
#[async_trait::async_trait(?Send)]
|
||||
impl Perform for GetCaptcha {
|
||||
type Response = GetCaptchaResponse;
|
||||
|
||||
#[tracing::instrument(skip(context))]
|
||||
async fn perform(&self, context: &Data<LemmyContext>) -> Result<Self::Response, LemmyError> {
|
||||
let local_site = LocalSite::read(context.pool()).await?;
|
||||
|
||||
if !local_site.captcha_enabled {
|
||||
return Ok(GetCaptchaResponse { ok: None });
|
||||
}
|
||||
|
||||
let captcha = gen(match local_site.captcha_difficulty.as_str() {
|
||||
"easy" => Difficulty::Easy,
|
||||
"hard" => Difficulty::Hard,
|
||||
_ => Difficulty::Medium,
|
||||
});
|
||||
|
||||
let answer = captcha.chars_as_string();
|
||||
|
||||
let png = captcha.as_base64().expect("failed to generate captcha");
|
||||
|
||||
let wav = captcha_as_wav_base64(&captcha);
|
||||
|
||||
let captcha_form: CaptchaAnswerForm = CaptchaAnswerForm { answer };
|
||||
// Stores the captcha item in the db
|
||||
let captcha = CaptchaAnswer::insert(context.pool(), &captcha_form).await?;
|
||||
|
||||
Ok(GetCaptchaResponse {
|
||||
ok: Some(CaptchaResponse {
|
||||
png,
|
||||
wav,
|
||||
uuid: captcha.uuid.to_string(),
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
@ -0,0 +1,118 @@
|
||||
use crate::{
|
||||
schema::captcha_answer::dsl::{answer, captcha_answer, uuid},
|
||||
source::captcha_answer::{CaptchaAnswer, CaptchaAnswerForm, CheckCaptchaAnswer},
|
||||
utils::{functions::lower, get_conn, DbPool},
|
||||
};
|
||||
use diesel::{
|
||||
delete,
|
||||
dsl::exists,
|
||||
insert_into,
|
||||
result::Error,
|
||||
select,
|
||||
ExpressionMethods,
|
||||
QueryDsl,
|
||||
};
|
||||
use diesel_async::RunQueryDsl;
|
||||
|
||||
impl CaptchaAnswer {
|
||||
pub async fn insert(pool: &DbPool, captcha: &CaptchaAnswerForm) -> Result<Self, Error> {
|
||||
let conn = &mut get_conn(pool).await?;
|
||||
|
||||
insert_into(captcha_answer)
|
||||
.values(captcha)
|
||||
.get_result::<Self>(conn)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn check_captcha(pool: &DbPool, to_check: CheckCaptchaAnswer) -> Result<bool, Error> {
|
||||
let conn = &mut get_conn(pool).await?;
|
||||
|
||||
// fetch requested captcha
|
||||
let captcha_exists = select(exists(
|
||||
captcha_answer
|
||||
.filter((uuid).eq(to_check.uuid))
|
||||
.filter(lower(answer).eq(to_check.answer.to_lowercase().clone())),
|
||||
))
|
||||
.get_result::<bool>(conn)
|
||||
.await?;
|
||||
|
||||
// delete checked captcha
|
||||
delete(captcha_answer.filter(uuid.eq(to_check.uuid)))
|
||||
.execute(conn)
|
||||
.await?;
|
||||
|
||||
Ok(captcha_exists)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
source::captcha_answer::{CaptchaAnswer, CaptchaAnswerForm, CheckCaptchaAnswer},
|
||||
utils::build_db_pool_for_tests,
|
||||
};
|
||||
use serial_test::serial;
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn test_captcha_happy_path() {
|
||||
let pool = &build_db_pool_for_tests().await;
|
||||
|
||||
let inserted = CaptchaAnswer::insert(
|
||||
pool,
|
||||
&CaptchaAnswerForm {
|
||||
answer: "XYZ".to_string(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("should not fail to insert captcha");
|
||||
|
||||
let result = CaptchaAnswer::check_captcha(
|
||||
pool,
|
||||
CheckCaptchaAnswer {
|
||||
uuid: inserted.uuid,
|
||||
answer: "xyz".to_string(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(result.is_ok());
|
||||
assert!(result.unwrap());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn test_captcha_repeat_answer_fails() {
|
||||
let pool = &build_db_pool_for_tests().await;
|
||||
|
||||
let inserted = CaptchaAnswer::insert(
|
||||
pool,
|
||||
&CaptchaAnswerForm {
|
||||
answer: "XYZ".to_string(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("should not fail to insert captcha");
|
||||
|
||||
let _result = CaptchaAnswer::check_captcha(
|
||||
pool,
|
||||
CheckCaptchaAnswer {
|
||||
uuid: inserted.uuid,
|
||||
answer: "xyz".to_string(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
let result_repeat = CaptchaAnswer::check_captcha(
|
||||
pool,
|
||||
CheckCaptchaAnswer {
|
||||
uuid: inserted.uuid,
|
||||
answer: "xyz".to_string(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(result_repeat.is_ok());
|
||||
assert!(!result_repeat.unwrap());
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
#[cfg(feature = "full")]
|
||||
use crate::schema::captcha_answer;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_with::skip_serializing_none;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[skip_serializing_none]
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "full", derive(Queryable))]
|
||||
#[cfg_attr(feature = "full", diesel(table_name = captcha_answer))]
|
||||
pub struct CaptchaAnswer {
|
||||
pub id: i32,
|
||||
pub uuid: Uuid,
|
||||
pub answer: String,
|
||||
pub published: chrono::NaiveDateTime,
|
||||
}
|
||||
|
||||
#[skip_serializing_none]
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "full", derive(Queryable))]
|
||||
#[cfg_attr(feature = "full", diesel(table_name = captcha_answer))]
|
||||
pub struct CheckCaptchaAnswer {
|
||||
pub uuid: Uuid,
|
||||
pub answer: String,
|
||||
}
|
||||
|
||||
#[skip_serializing_none]
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "full", derive(Insertable, AsChangeset))]
|
||||
#[cfg_attr(feature = "full", diesel(table_name = captcha_answer))]
|
||||
pub struct CaptchaAnswerForm {
|
||||
pub answer: String,
|
||||
}
|
@ -0,0 +1 @@
|
||||
drop table captcha_answer;
|
@ -0,0 +1,6 @@
|
||||
create table captcha_answer (
|
||||
id serial primary key,
|
||||
uuid uuid not null unique default gen_random_uuid(),
|
||||
answer text not null,
|
||||
published timestamp not null default now()
|
||||
);
|
Loading…
Reference in New Issue