]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/get_captcha.rs
feat: re-added captcha checks (#3249)
[lemmy.git] / crates / api / src / local_user / get_captcha.rs
1 use crate::{captcha_as_wav_base64, Perform};
2 use actix_web::web::Data;
3 use captcha::{gen, Difficulty};
4 use chrono::Duration;
5 use lemmy_api_common::{
6   context::LemmyContext,
7   person::{CaptchaResponse, GetCaptcha, GetCaptchaResponse},
8 };
9 use lemmy_db_schema::{
10   source::{captcha_answer::CaptchaAnswer, local_site::LocalSite},
11   utils::naive_now,
12 };
13 use lemmy_utils::error::LemmyError;
14
15 #[async_trait::async_trait(?Send)]
16 impl Perform for GetCaptcha {
17   type Response = GetCaptchaResponse;
18
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?;
22
23     if !local_site.captcha_enabled {
24       return Ok(GetCaptchaResponse { ok: None });
25     }
26
27     let captcha = gen(match local_site.captcha_difficulty.as_str() {
28       "easy" => Difficulty::Easy,
29       "hard" => Difficulty::Hard,
30       _ => Difficulty::Medium,
31     });
32
33     let answer = captcha.chars_as_string();
34
35     let png = captcha.as_base64().expect("failed to generate captcha");
36
37     let uuid = uuid::Uuid::new_v4().to_string();
38
39     let wav = captcha_as_wav_base64(&captcha);
40
41     let captcha: CaptchaAnswer = CaptchaAnswer {
42       answer,
43       uuid: uuid.clone(),
44       expires: naive_now() + Duration::minutes(10), // expires in 10 minutes
45     };
46     // Stores the captcha item in the db
47     CaptchaAnswer::insert(context.pool(), &captcha).await?;
48
49     Ok(GetCaptchaResponse {
50       ok: Some(CaptchaResponse { png, wav, uuid }),
51     })
52   }
53 }