2023-09-05 09:33:46 +00:00
|
|
|
use crate::captcha_as_wav_base64;
|
|
|
|
use actix_web::web::{Data, Json};
|
2023-06-27 10:38:53 +00:00
|
|
|
use captcha::{gen, Difficulty};
|
|
|
|
use lemmy_api_common::{
|
|
|
|
context::LemmyContext,
|
2023-09-05 09:33:46 +00:00
|
|
|
person::{CaptchaResponse, GetCaptchaResponse},
|
2023-06-27 10:38:53 +00:00
|
|
|
};
|
|
|
|
use lemmy_db_schema::source::{
|
|
|
|
captcha_answer::{CaptchaAnswer, CaptchaAnswerForm},
|
|
|
|
local_site::LocalSite,
|
|
|
|
};
|
|
|
|
use lemmy_utils::error::LemmyError;
|
|
|
|
|
2023-09-05 09:33:46 +00:00
|
|
|
#[tracing::instrument(skip(context))]
|
|
|
|
pub async fn get_captcha(
|
|
|
|
context: Data<LemmyContext>,
|
|
|
|
) -> Result<Json<GetCaptchaResponse>, LemmyError> {
|
|
|
|
let local_site = LocalSite::read(&mut context.pool()).await?;
|
2023-06-27 10:38:53 +00:00
|
|
|
|
2023-09-05 09:33:46 +00:00
|
|
|
if !local_site.captcha_enabled {
|
|
|
|
return Ok(Json(GetCaptchaResponse { ok: None }));
|
|
|
|
}
|
2023-06-27 10:38:53 +00:00
|
|
|
|
2023-09-05 09:33:46 +00:00
|
|
|
let captcha = gen(match local_site.captcha_difficulty.as_str() {
|
|
|
|
"easy" => Difficulty::Easy,
|
|
|
|
"hard" => Difficulty::Hard,
|
|
|
|
_ => Difficulty::Medium,
|
|
|
|
});
|
2023-06-27 10:38:53 +00:00
|
|
|
|
2023-09-05 09:33:46 +00:00
|
|
|
let answer = captcha.chars_as_string();
|
2023-06-27 10:38:53 +00:00
|
|
|
|
2023-09-05 09:33:46 +00:00
|
|
|
let png = captcha.as_base64().expect("failed to generate captcha");
|
2023-06-27 10:38:53 +00:00
|
|
|
|
2023-09-05 09:33:46 +00:00
|
|
|
let wav = captcha_as_wav_base64(&captcha)?;
|
2023-06-27 10:38:53 +00:00
|
|
|
|
2023-09-05 09:33:46 +00:00
|
|
|
let captcha_form: CaptchaAnswerForm = CaptchaAnswerForm { answer };
|
|
|
|
// Stores the captcha item in the db
|
|
|
|
let captcha = CaptchaAnswer::insert(&mut context.pool(), &captcha_form).await?;
|
2023-06-27 10:38:53 +00:00
|
|
|
|
2023-09-05 09:33:46 +00:00
|
|
|
Ok(Json(GetCaptchaResponse {
|
|
|
|
ok: Some(CaptchaResponse {
|
|
|
|
png,
|
|
|
|
wav,
|
|
|
|
uuid: captcha.uuid.to_string(),
|
|
|
|
}),
|
|
|
|
}))
|
2023-06-27 10:38:53 +00:00
|
|
|
}
|