1 use crate::{captcha_as_wav_base64, Perform};
2 use actix_web::web::Data;
3 use captcha::{gen, Difficulty};
5 use lemmy_api_common::{
7 person::{CaptchaResponse, GetCaptcha, GetCaptchaResponse},
10 source::{captcha_answer::CaptchaAnswer, local_site::LocalSite},
13 use lemmy_utils::error::LemmyError;
15 #[async_trait::async_trait(?Send)]
16 impl Perform for GetCaptcha {
17 type Response = GetCaptchaResponse;
19 #[tracing::instrument(skip(context))]
20 async fn perform(&self, context: &Data<LemmyContext>) -> Result<Self::Response, LemmyError> {
21 let local_site = LocalSite::read(context.pool()).await?;
23 if !local_site.captcha_enabled {
24 return Ok(GetCaptchaResponse { ok: None });
27 let captcha = gen(match local_site.captcha_difficulty.as_str() {
28 "easy" => Difficulty::Easy,
29 "hard" => Difficulty::Hard,
30 _ => Difficulty::Medium,
33 let answer = captcha.chars_as_string();
35 let png = captcha.as_base64().expect("failed to generate captcha");
37 let uuid = uuid::Uuid::new_v4().to_string();
39 let wav = captcha_as_wav_base64(&captcha);
41 let captcha: CaptchaAnswer = CaptchaAnswer {
44 expires: naive_now() + Duration::minutes(10), // expires in 10 minutes
46 // Stores the captcha item in the db
47 CaptchaAnswer::insert(context.pool(), &captcha).await?;
49 Ok(GetCaptchaResponse {
50 ok: Some(CaptchaResponse { png, wav, uuid }),