]> Untitled Git - lemmy.git/blob - crates/api/src/lib.rs
3cffe016642f80730e07ee4bb251007b0be0d7f3
[lemmy.git] / crates / api / src / lib.rs
1 use actix_web::{web, web::Data};
2 use captcha::Captcha;
3 use lemmy_api_common::{comment::*, community::*, person::*, post::*, site::*, websocket::*};
4 use lemmy_utils::{ConnectionId, LemmyError};
5 use lemmy_websocket::{serialize_websocket_message, LemmyContext, UserOperation};
6 use serde::Deserialize;
7
8 mod comment;
9 mod comment_report;
10 mod community;
11 mod local_user;
12 mod post;
13 mod post_report;
14 mod private_message;
15 mod site;
16 mod websocket;
17
18 #[async_trait::async_trait(?Send)]
19 pub trait Perform {
20   type Response: serde::ser::Serialize + Send;
21
22   async fn perform(
23     &self,
24     context: &Data<LemmyContext>,
25     websocket_id: Option<ConnectionId>,
26   ) -> Result<Self::Response, LemmyError>;
27 }
28
29 pub async fn match_websocket_operation(
30   context: LemmyContext,
31   id: ConnectionId,
32   op: UserOperation,
33   data: &str,
34 ) -> Result<String, LemmyError> {
35   match op {
36     // User ops
37     UserOperation::Login => do_websocket_operation::<Login>(context, id, op, data).await,
38     UserOperation::GetCaptcha => do_websocket_operation::<GetCaptcha>(context, id, op, data).await,
39     UserOperation::GetReplies => do_websocket_operation::<GetReplies>(context, id, op, data).await,
40     UserOperation::AddAdmin => do_websocket_operation::<AddAdmin>(context, id, op, data).await,
41     UserOperation::GetUnreadRegistrationApplicationCount => {
42       do_websocket_operation::<GetUnreadRegistrationApplicationCount>(context, id, op, data).await
43     }
44     UserOperation::ListRegistrationApplications => {
45       do_websocket_operation::<ListRegistrationApplications>(context, id, op, data).await
46     }
47     UserOperation::ApproveRegistrationApplication => {
48       do_websocket_operation::<ApproveRegistrationApplication>(context, id, op, data).await
49     }
50     UserOperation::BanPerson => do_websocket_operation::<BanPerson>(context, id, op, data).await,
51     UserOperation::GetBannedPersons => {
52       do_websocket_operation::<GetBannedPersons>(context, id, op, data).await
53     }
54     UserOperation::BlockPerson => {
55       do_websocket_operation::<BlockPerson>(context, id, op, data).await
56     }
57     UserOperation::GetPersonMentions => {
58       do_websocket_operation::<GetPersonMentions>(context, id, op, data).await
59     }
60     UserOperation::MarkPersonMentionAsRead => {
61       do_websocket_operation::<MarkPersonMentionAsRead>(context, id, op, data).await
62     }
63     UserOperation::MarkAllAsRead => {
64       do_websocket_operation::<MarkAllAsRead>(context, id, op, data).await
65     }
66     UserOperation::PasswordReset => {
67       do_websocket_operation::<PasswordReset>(context, id, op, data).await
68     }
69     UserOperation::PasswordChange => {
70       do_websocket_operation::<PasswordChange>(context, id, op, data).await
71     }
72     UserOperation::UserJoin => do_websocket_operation::<UserJoin>(context, id, op, data).await,
73     UserOperation::PostJoin => do_websocket_operation::<PostJoin>(context, id, op, data).await,
74     UserOperation::CommunityJoin => {
75       do_websocket_operation::<CommunityJoin>(context, id, op, data).await
76     }
77     UserOperation::ModJoin => do_websocket_operation::<ModJoin>(context, id, op, data).await,
78     UserOperation::SaveUserSettings => {
79       do_websocket_operation::<SaveUserSettings>(context, id, op, data).await
80     }
81     UserOperation::ChangePassword => {
82       do_websocket_operation::<ChangePassword>(context, id, op, data).await
83     }
84     UserOperation::GetReportCount => {
85       do_websocket_operation::<GetReportCount>(context, id, op, data).await
86     }
87     UserOperation::GetUnreadCount => {
88       do_websocket_operation::<GetUnreadCount>(context, id, op, data).await
89     }
90     UserOperation::VerifyEmail => {
91       do_websocket_operation::<VerifyEmail>(context, id, op, data).await
92     }
93
94     // Private Message ops
95     UserOperation::MarkPrivateMessageAsRead => {
96       do_websocket_operation::<MarkPrivateMessageAsRead>(context, id, op, data).await
97     }
98
99     // Site ops
100     UserOperation::GetModlog => do_websocket_operation::<GetModlog>(context, id, op, data).await,
101     UserOperation::GetSiteConfig => {
102       do_websocket_operation::<GetSiteConfig>(context, id, op, data).await
103     }
104     UserOperation::SaveSiteConfig => {
105       do_websocket_operation::<SaveSiteConfig>(context, id, op, data).await
106     }
107     UserOperation::Search => do_websocket_operation::<Search>(context, id, op, data).await,
108     UserOperation::ResolveObject => {
109       do_websocket_operation::<ResolveObject>(context, id, op, data).await
110     }
111     UserOperation::TransferCommunity => {
112       do_websocket_operation::<TransferCommunity>(context, id, op, data).await
113     }
114     UserOperation::TransferSite => {
115       do_websocket_operation::<TransferSite>(context, id, op, data).await
116     }
117
118     // Community ops
119     UserOperation::FollowCommunity => {
120       do_websocket_operation::<FollowCommunity>(context, id, op, data).await
121     }
122     UserOperation::BlockCommunity => {
123       do_websocket_operation::<BlockCommunity>(context, id, op, data).await
124     }
125     UserOperation::BanFromCommunity => {
126       do_websocket_operation::<BanFromCommunity>(context, id, op, data).await
127     }
128     UserOperation::AddModToCommunity => {
129       do_websocket_operation::<AddModToCommunity>(context, id, op, data).await
130     }
131
132     // Post ops
133     UserOperation::LockPost => do_websocket_operation::<LockPost>(context, id, op, data).await,
134     UserOperation::StickyPost => do_websocket_operation::<StickyPost>(context, id, op, data).await,
135     UserOperation::CreatePostLike => {
136       do_websocket_operation::<CreatePostLike>(context, id, op, data).await
137     }
138     UserOperation::MarkPostAsRead => {
139       do_websocket_operation::<MarkPostAsRead>(context, id, op, data).await
140     }
141     UserOperation::SavePost => do_websocket_operation::<SavePost>(context, id, op, data).await,
142     UserOperation::CreatePostReport => {
143       do_websocket_operation::<CreatePostReport>(context, id, op, data).await
144     }
145     UserOperation::ListPostReports => {
146       do_websocket_operation::<ListPostReports>(context, id, op, data).await
147     }
148     UserOperation::ResolvePostReport => {
149       do_websocket_operation::<ResolvePostReport>(context, id, op, data).await
150     }
151     UserOperation::GetSiteMetadata => {
152       do_websocket_operation::<GetSiteMetadata>(context, id, op, data).await
153     }
154
155     // Comment ops
156     UserOperation::MarkCommentAsRead => {
157       do_websocket_operation::<MarkCommentAsRead>(context, id, op, data).await
158     }
159     UserOperation::SaveComment => {
160       do_websocket_operation::<SaveComment>(context, id, op, data).await
161     }
162     UserOperation::CreateCommentLike => {
163       do_websocket_operation::<CreateCommentLike>(context, id, op, data).await
164     }
165     UserOperation::CreateCommentReport => {
166       do_websocket_operation::<CreateCommentReport>(context, id, op, data).await
167     }
168     UserOperation::ListCommentReports => {
169       do_websocket_operation::<ListCommentReports>(context, id, op, data).await
170     }
171     UserOperation::ResolveCommentReport => {
172       do_websocket_operation::<ResolveCommentReport>(context, id, op, data).await
173     }
174   }
175 }
176
177 async fn do_websocket_operation<'a, 'b, Data>(
178   context: LemmyContext,
179   id: ConnectionId,
180   op: UserOperation,
181   data: &str,
182 ) -> Result<String, LemmyError>
183 where
184   for<'de> Data: Deserialize<'de> + 'a,
185   Data: Perform,
186 {
187   let parsed_data: Data = serde_json::from_str(data)?;
188   let res = parsed_data
189     .perform(&web::Data::new(context), Some(id))
190     .await?;
191   serialize_websocket_message(&op, &res)
192 }
193
194 /// Converts the captcha to a base64 encoded wav audio file
195 pub(crate) fn captcha_as_wav_base64(captcha: &Captcha) -> String {
196   let letters = captcha.as_wav();
197
198   let mut concat_letters: Vec<u8> = Vec::new();
199
200   for letter in letters {
201     let bytes = letter.unwrap_or_default();
202     concat_letters.extend(bytes);
203   }
204
205   // Convert to base64
206   base64::encode(concat_letters)
207 }
208
209 #[cfg(test)]
210 mod tests {
211   use lemmy_api_common::check_validator_time;
212   use lemmy_db_schema::{
213     establish_unpooled_connection,
214     source::{
215       local_user::{LocalUser, LocalUserForm},
216       person::{Person, PersonForm},
217       secret::Secret,
218     },
219     traits::Crud,
220   };
221   use lemmy_utils::{claims::Claims, settings::structs::Settings};
222
223   #[test]
224   fn test_should_not_validate_user_token_after_password_change() {
225     let conn = establish_unpooled_connection();
226     let secret = Secret::init(&conn).unwrap();
227     let settings = Settings::init().unwrap();
228
229     let new_person = PersonForm {
230       name: "Gerry9812".into(),
231       ..PersonForm::default()
232     };
233
234     let inserted_person = Person::create(&conn, &new_person).unwrap();
235
236     let local_user_form = LocalUserForm {
237       person_id: Some(inserted_person.id),
238       password_encrypted: Some("123456".to_string()),
239       ..LocalUserForm::default()
240     };
241
242     let inserted_local_user = LocalUser::create(&conn, &local_user_form).unwrap();
243
244     let jwt = Claims::jwt(
245       inserted_local_user.id.0,
246       &secret.jwt_secret,
247       &settings.hostname,
248     )
249     .unwrap();
250     let claims = Claims::decode(&jwt, &secret.jwt_secret).unwrap().claims;
251     let check = check_validator_time(&inserted_local_user.validator_time, &claims);
252     assert!(check.is_ok());
253
254     // The check should fail, since the validator time is now newer than the jwt issue time
255     let updated_local_user =
256       LocalUser::update_password(&conn, inserted_local_user.id, "password111").unwrap();
257     let check_after = check_validator_time(&updated_local_user.validator_time, &claims);
258     assert!(check_after.is_err());
259
260     let num_deleted = Person::delete(&conn, inserted_person.id).unwrap();
261     assert_eq!(1, num_deleted);
262   }
263 }