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},
8 websocket::messages::CaptchaItem,
10 use lemmy_db_schema::{source::local_site::LocalSite, utils::naive_now};
11 use lemmy_utils::{error::LemmyError, ConnectionId};
13 #[async_trait::async_trait(?Send)]
14 impl Perform for GetCaptcha {
15 type Response = GetCaptchaResponse;
17 #[tracing::instrument(skip(context, _websocket_id))]
20 context: &Data<LemmyContext>,
21 _websocket_id: Option<ConnectionId>,
22 ) -> Result<Self::Response, LemmyError> {
23 let local_site = LocalSite::read(context.pool()).await?;
25 if !local_site.captcha_enabled {
26 return Ok(GetCaptchaResponse { ok: None });
29 let captcha = gen(match local_site.captcha_difficulty.as_str() {
30 "easy" => Difficulty::Easy,
31 "hard" => Difficulty::Hard,
32 _ => Difficulty::Medium,
35 let answer = captcha.chars_as_string();
37 let png = captcha.as_base64().expect("failed to generate captcha");
39 let uuid = uuid::Uuid::new_v4().to_string();
41 let wav = captcha_as_wav_base64(&captcha);
43 let captcha_item = CaptchaItem {
46 expires: naive_now() + Duration::minutes(10), // expires in 10 minutes
49 // Stores the captcha item on the queue
50 context.chat_server().do_send(captcha_item);
52 Ok(GetCaptchaResponse {
53 ok: Some(CaptchaResponse { png, wav, uuid }),