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