]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/get_captcha.rs
Split apart api files (#2216)
[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::person::{CaptchaResponse, GetCaptcha, GetCaptchaResponse};
6 use lemmy_db_schema::naive_now;
7 use lemmy_utils::{ConnectionId, LemmyError};
8 use lemmy_websocket::{messages::CaptchaItem, LemmyContext};
9
10 #[async_trait::async_trait(?Send)]
11 impl Perform for GetCaptcha {
12   type Response = GetCaptchaResponse;
13
14   #[tracing::instrument(skip(context, _websocket_id))]
15   async fn perform(
16     &self,
17     context: &Data<LemmyContext>,
18     _websocket_id: Option<ConnectionId>,
19   ) -> Result<Self::Response, LemmyError> {
20     let captcha_settings = context.settings().captcha;
21
22     if !captcha_settings.enabled {
23       return Ok(GetCaptchaResponse { ok: None });
24     }
25
26     let captcha = gen(match captcha_settings.difficulty.as_str() {
27       "easy" => Difficulty::Easy,
28       "hard" => Difficulty::Hard,
29       _ => Difficulty::Medium,
30     });
31
32     let answer = captcha.chars_as_string();
33
34     let png = captcha.as_base64().expect("failed to generate captcha");
35
36     let uuid = uuid::Uuid::new_v4().to_string();
37
38     let wav = captcha_as_wav_base64(&captcha);
39
40     let captcha_item = CaptchaItem {
41       answer,
42       uuid: uuid.to_owned(),
43       expires: naive_now() + Duration::minutes(10), // expires in 10 minutes
44     };
45
46     // Stores the captcha item on the queue
47     context.chat_server().do_send(captcha_item);
48
49     Ok(GetCaptchaResponse {
50       ok: Some(CaptchaResponse { png, wav, uuid }),
51     })
52   }
53 }