]> Untitled Git - lemmy.git/blob - crates/api/src/lib.rs
026045dd2a0c7f368f8fcb8f4491f958fda18391
[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::{error::LemmyError, ConnectionId};
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::MarkCommentReplyAsRead => {
64       do_websocket_operation::<MarkCommentReplyAsRead>(context, id, op, data).await
65     }
66     UserOperation::MarkAllAsRead => {
67       do_websocket_operation::<MarkAllAsRead>(context, id, op, data).await
68     }
69     UserOperation::PasswordReset => {
70       do_websocket_operation::<PasswordReset>(context, id, op, data).await
71     }
72     UserOperation::PasswordChange => {
73       do_websocket_operation::<PasswordChangeAfterReset>(context, id, op, data).await
74     }
75     UserOperation::UserJoin => do_websocket_operation::<UserJoin>(context, id, op, data).await,
76     UserOperation::PostJoin => do_websocket_operation::<PostJoin>(context, id, op, data).await,
77     UserOperation::CommunityJoin => {
78       do_websocket_operation::<CommunityJoin>(context, id, op, data).await
79     }
80     UserOperation::ModJoin => do_websocket_operation::<ModJoin>(context, id, op, data).await,
81     UserOperation::SaveUserSettings => {
82       do_websocket_operation::<SaveUserSettings>(context, id, op, data).await
83     }
84     UserOperation::ChangePassword => {
85       do_websocket_operation::<ChangePassword>(context, id, op, data).await
86     }
87     UserOperation::GetReportCount => {
88       do_websocket_operation::<GetReportCount>(context, id, op, data).await
89     }
90     UserOperation::GetUnreadCount => {
91       do_websocket_operation::<GetUnreadCount>(context, id, op, data).await
92     }
93     UserOperation::VerifyEmail => {
94       do_websocket_operation::<VerifyEmail>(context, id, op, data).await
95     }
96
97     // Private Message ops
98     UserOperation::MarkPrivateMessageAsRead => {
99       do_websocket_operation::<MarkPrivateMessageAsRead>(context, id, op, data).await
100     }
101
102     // Site ops
103     UserOperation::GetModlog => do_websocket_operation::<GetModlog>(context, id, op, data).await,
104     UserOperation::PurgePerson => {
105       do_websocket_operation::<PurgePerson>(context, id, op, data).await
106     }
107     UserOperation::PurgeCommunity => {
108       do_websocket_operation::<PurgeCommunity>(context, id, op, data).await
109     }
110     UserOperation::PurgePost => do_websocket_operation::<PurgePost>(context, id, op, data).await,
111     UserOperation::PurgeComment => {
112       do_websocket_operation::<PurgeComment>(context, id, op, data).await
113     }
114     UserOperation::Search => do_websocket_operation::<Search>(context, id, op, data).await,
115     UserOperation::ResolveObject => {
116       do_websocket_operation::<ResolveObject>(context, id, op, data).await
117     }
118     UserOperation::TransferCommunity => {
119       do_websocket_operation::<TransferCommunity>(context, id, op, data).await
120     }
121     UserOperation::LeaveAdmin => do_websocket_operation::<LeaveAdmin>(context, id, op, data).await,
122
123     // Community ops
124     UserOperation::FollowCommunity => {
125       do_websocket_operation::<FollowCommunity>(context, id, op, data).await
126     }
127     UserOperation::BlockCommunity => {
128       do_websocket_operation::<BlockCommunity>(context, id, op, data).await
129     }
130     UserOperation::BanFromCommunity => {
131       do_websocket_operation::<BanFromCommunity>(context, id, op, data).await
132     }
133     UserOperation::AddModToCommunity => {
134       do_websocket_operation::<AddModToCommunity>(context, id, op, data).await
135     }
136
137     // Post ops
138     UserOperation::LockPost => do_websocket_operation::<LockPost>(context, id, op, data).await,
139     UserOperation::StickyPost => do_websocket_operation::<StickyPost>(context, id, op, data).await,
140     UserOperation::CreatePostLike => {
141       do_websocket_operation::<CreatePostLike>(context, id, op, data).await
142     }
143     UserOperation::MarkPostAsRead => {
144       do_websocket_operation::<MarkPostAsRead>(context, id, op, data).await
145     }
146     UserOperation::SavePost => do_websocket_operation::<SavePost>(context, id, op, data).await,
147     UserOperation::CreatePostReport => {
148       do_websocket_operation::<CreatePostReport>(context, id, op, data).await
149     }
150     UserOperation::ListPostReports => {
151       do_websocket_operation::<ListPostReports>(context, id, op, data).await
152     }
153     UserOperation::ResolvePostReport => {
154       do_websocket_operation::<ResolvePostReport>(context, id, op, data).await
155     }
156     UserOperation::GetSiteMetadata => {
157       do_websocket_operation::<GetSiteMetadata>(context, id, op, data).await
158     }
159
160     // Comment ops
161     UserOperation::SaveComment => {
162       do_websocket_operation::<SaveComment>(context, id, op, data).await
163     }
164     UserOperation::CreateCommentLike => {
165       do_websocket_operation::<CreateCommentLike>(context, id, op, data).await
166     }
167     UserOperation::CreateCommentReport => {
168       do_websocket_operation::<CreateCommentReport>(context, id, op, data).await
169     }
170     UserOperation::ListCommentReports => {
171       do_websocket_operation::<ListCommentReports>(context, id, op, data).await
172     }
173     UserOperation::ResolveCommentReport => {
174       do_websocket_operation::<ResolveCommentReport>(context, id, op, data).await
175     }
176   }
177 }
178
179 async fn do_websocket_operation<'a, 'b, Data>(
180   context: LemmyContext,
181   id: ConnectionId,
182   op: UserOperation,
183   data: &str,
184 ) -> Result<String, LemmyError>
185 where
186   for<'de> Data: Deserialize<'de> + 'a,
187   Data: Perform,
188 {
189   let parsed_data: Data = serde_json::from_str(data)?;
190   let res = parsed_data
191     .perform(&web::Data::new(context), Some(id))
192     .await?;
193   serialize_websocket_message(&op, &res)
194 }
195
196 /// Converts the captcha to a base64 encoded wav audio file
197 pub(crate) fn captcha_as_wav_base64(captcha: &Captcha) -> String {
198   let letters = captcha.as_wav();
199
200   let mut concat_letters: Vec<u8> = Vec::new();
201
202   for letter in letters {
203     let bytes = letter.unwrap_or_default();
204     concat_letters.extend(bytes);
205   }
206
207   // Convert to base64
208   base64::encode(concat_letters)
209 }
210
211 #[cfg(test)]
212 mod tests {
213   use lemmy_api_common::utils::check_validator_time;
214   use lemmy_db_schema::{
215     source::{
216       local_user::{LocalUser, LocalUserForm},
217       person::{Person, PersonForm},
218       secret::Secret,
219     },
220     traits::Crud,
221     utils::establish_unpooled_connection,
222   };
223   use lemmy_utils::{claims::Claims, settings::SETTINGS};
224
225   #[test]
226   fn test_should_not_validate_user_token_after_password_change() {
227     let conn = establish_unpooled_connection();
228     let secret = Secret::init(&conn).unwrap();
229     let settings = &SETTINGS.to_owned();
230
231     let new_person = PersonForm {
232       name: "Gerry9812".into(),
233       public_key: Some("pubkey".to_string()),
234       ..PersonForm::default()
235     };
236
237     let inserted_person = Person::create(&conn, &new_person).unwrap();
238
239     let local_user_form = LocalUserForm {
240       person_id: Some(inserted_person.id),
241       password_encrypted: Some("123456".to_string()),
242       ..LocalUserForm::default()
243     };
244
245     let inserted_local_user = LocalUser::create(&conn, &local_user_form).unwrap();
246
247     let jwt = Claims::jwt(
248       inserted_local_user.id.0,
249       &secret.jwt_secret,
250       &settings.hostname,
251     )
252     .unwrap();
253     let claims = Claims::decode(&jwt, &secret.jwt_secret).unwrap().claims;
254     let check = check_validator_time(&inserted_local_user.validator_time, &claims);
255     assert!(check.is_ok());
256
257     // The check should fail, since the validator time is now newer than the jwt issue time
258     let updated_local_user =
259       LocalUser::update_password(&conn, inserted_local_user.id, "password111").unwrap();
260     let check_after = check_validator_time(&updated_local_user.validator_time, &claims);
261     assert!(check_after.is_err());
262
263     let num_deleted = Person::delete(&conn, inserted_person.id).unwrap();
264     assert_eq!(1, num_deleted);
265   }
266 }