]> Untitled Git - lemmy.git/blob - crates/api_common/src/lib.rs
Don't allow deleted users to do actions. Fixes #1656 (#1704)
[lemmy.git] / crates / api_common / src / lib.rs
1 pub mod comment;
2 pub mod community;
3 pub mod person;
4 pub mod post;
5 pub mod site;
6 pub mod websocket;
7
8 use crate::site::FederatedInstances;
9 use diesel::PgConnection;
10 use lemmy_db_queries::{
11   source::{
12     community::{CommunityModerator_, Community_},
13     site::Site_,
14   },
15   Crud,
16   DbPool,
17   Readable,
18 };
19 use lemmy_db_schema::{
20   source::{
21     comment::Comment,
22     community::{Community, CommunityModerator},
23     person::Person,
24     person_mention::{PersonMention, PersonMentionForm},
25     post::{Post, PostRead, PostReadForm},
26     site::Site,
27   },
28   CommunityId,
29   LocalUserId,
30   PersonId,
31   PostId,
32 };
33 use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView};
34 use lemmy_db_views_actor::{
35   community_person_ban_view::CommunityPersonBanView,
36   community_view::CommunityView,
37 };
38 use lemmy_utils::{
39   claims::Claims,
40   email::send_email,
41   settings::structs::Settings,
42   utils::MentionData,
43   ApiError,
44   LemmyError,
45 };
46 use log::error;
47 use serde::{Deserialize, Serialize};
48 use url::Url;
49
50 #[derive(Serialize, Deserialize, Debug)]
51 pub struct WebFingerLink {
52   pub rel: Option<String>,
53   #[serde(rename(serialize = "type", deserialize = "type"))]
54   pub type_: Option<String>,
55   pub href: Option<Url>,
56   #[serde(skip_serializing_if = "Option::is_none")]
57   pub template: Option<String>,
58 }
59
60 #[derive(Serialize, Deserialize, Debug)]
61 pub struct WebFingerResponse {
62   pub subject: String,
63   pub aliases: Vec<Url>,
64   pub links: Vec<WebFingerLink>,
65 }
66
67 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
68 where
69   F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
70   T: Send + 'static,
71 {
72   let pool = pool.clone();
73   let res = actix_web::web::block(move || {
74     let conn = pool.get()?;
75     let res = (f)(&conn);
76     Ok(res) as Result<T, LemmyError>
77   })
78   .await?;
79
80   res
81 }
82
83 pub async fn send_local_notifs(
84   mentions: Vec<MentionData>,
85   comment: Comment,
86   person: Person,
87   post: Post,
88   pool: &DbPool,
89   do_send_email: bool,
90 ) -> Result<Vec<LocalUserId>, LemmyError> {
91   let ids = blocking(pool, move |conn| {
92     do_send_local_notifs(conn, &mentions, &comment, &person, &post, do_send_email)
93   })
94   .await?;
95
96   Ok(ids)
97 }
98
99 fn do_send_local_notifs(
100   conn: &PgConnection,
101   mentions: &[MentionData],
102   comment: &Comment,
103   person: &Person,
104   post: &Post,
105   do_send_email: bool,
106 ) -> Vec<LocalUserId> {
107   let mut recipient_ids = Vec::new();
108
109   // Send the local mentions
110   for mention in mentions
111     .iter()
112     .filter(|m| m.is_local() && m.name.ne(&person.name))
113     .collect::<Vec<&MentionData>>()
114   {
115     if let Ok(mention_user_view) = LocalUserView::read_from_name(conn, &mention.name) {
116       // TODO
117       // At some point, make it so you can't tag the parent creator either
118       // This can cause two notifications, one for reply and the other for mention
119       recipient_ids.push(mention_user_view.local_user.id);
120
121       let user_mention_form = PersonMentionForm {
122         recipient_id: mention_user_view.person.id,
123         comment_id: comment.id,
124         read: None,
125       };
126
127       // Allow this to fail softly, since comment edits might re-update or replace it
128       // Let the uniqueness handle this fail
129       PersonMention::create(conn, &user_mention_form).ok();
130
131       // Send an email to those local users that have notifications on
132       if do_send_email {
133         send_email_to_user(
134           &mention_user_view,
135           "Mentioned by",
136           "Person Mention",
137           &comment.content,
138         )
139       }
140     }
141   }
142
143   // Send notifs to the parent commenter / poster
144   match comment.parent_id {
145     Some(parent_id) => {
146       if let Ok(parent_comment) = Comment::read(conn, parent_id) {
147         // Don't send a notif to yourself
148         if parent_comment.creator_id != person.id {
149           // Get the parent commenter local_user
150           if let Ok(parent_user_view) = LocalUserView::read_person(conn, parent_comment.creator_id)
151           {
152             recipient_ids.push(parent_user_view.local_user.id);
153
154             if do_send_email {
155               send_email_to_user(
156                 &parent_user_view,
157                 "Reply from",
158                 "Comment Reply",
159                 &comment.content,
160               )
161             }
162           }
163         }
164       }
165     }
166     // Its a post
167     None => {
168       if post.creator_id != person.id {
169         if let Ok(parent_user_view) = LocalUserView::read_person(conn, post.creator_id) {
170           recipient_ids.push(parent_user_view.local_user.id);
171
172           if do_send_email {
173             send_email_to_user(
174               &parent_user_view,
175               "Reply from",
176               "Post Reply",
177               &comment.content,
178             )
179           }
180         }
181       }
182     }
183   };
184   recipient_ids
185 }
186
187 pub fn send_email_to_user(
188   local_user_view: &LocalUserView,
189   subject_text: &str,
190   body_text: &str,
191   comment_content: &str,
192 ) {
193   if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
194     return;
195   }
196
197   if let Some(user_email) = &local_user_view.local_user.email {
198     let subject = &format!(
199       "{} - {} {}",
200       subject_text,
201       Settings::get().hostname,
202       local_user_view.person.name,
203     );
204     let html = &format!(
205       "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
206       body_text,
207       local_user_view.person.name,
208       comment_content,
209       Settings::get().get_protocol_and_hostname()
210     );
211     match send_email(subject, user_email, &local_user_view.person.name, html) {
212       Ok(_o) => _o,
213       Err(e) => error!("{}", e),
214     };
215   }
216 }
217
218 pub async fn is_mod_or_admin(
219   pool: &DbPool,
220   person_id: PersonId,
221   community_id: CommunityId,
222 ) -> Result<(), LemmyError> {
223   let is_mod_or_admin = blocking(pool, move |conn| {
224     CommunityView::is_mod_or_admin(conn, person_id, community_id)
225   })
226   .await?;
227   if !is_mod_or_admin {
228     return Err(ApiError::err("not_a_mod_or_admin").into());
229   }
230   Ok(())
231 }
232
233 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
234   if !local_user_view.person.admin {
235     return Err(ApiError::err("not_an_admin").into());
236   }
237   Ok(())
238 }
239
240 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
241   blocking(pool, move |conn| Post::read(conn, post_id))
242     .await?
243     .map_err(|_| ApiError::err("couldnt_find_post").into())
244 }
245
246 pub async fn mark_post_as_read(
247   person_id: PersonId,
248   post_id: PostId,
249   pool: &DbPool,
250 ) -> Result<PostRead, LemmyError> {
251   let post_read_form = PostReadForm { post_id, person_id };
252
253   blocking(pool, move |conn| {
254     PostRead::mark_as_read(conn, &post_read_form)
255   })
256   .await?
257   .map_err(|_| ApiError::err("couldnt_mark_post_as_read").into())
258 }
259
260 pub async fn get_local_user_view_from_jwt(
261   jwt: &str,
262   pool: &DbPool,
263 ) -> Result<LocalUserView, LemmyError> {
264   let claims = Claims::decode(jwt)
265     .map_err(|_| ApiError::err("not_logged_in"))?
266     .claims;
267   let local_user_id = LocalUserId(claims.sub);
268   let local_user_view =
269     blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
270   // Check for a site ban
271   if local_user_view.person.banned {
272     return Err(ApiError::err("site_ban").into());
273   }
274
275   // Check for user deletion
276   if local_user_view.person.deleted {
277     return Err(ApiError::err("deleted").into());
278   }
279
280   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
281
282   Ok(local_user_view)
283 }
284
285 /// Checks if user's token was issued before user's password reset.
286 pub fn check_validator_time(
287   validator_time: &chrono::NaiveDateTime,
288   claims: &Claims,
289 ) -> Result<(), LemmyError> {
290   let user_validation_time = validator_time.timestamp();
291   if user_validation_time > claims.iat {
292     Err(ApiError::err("not_logged_in").into())
293   } else {
294     Ok(())
295   }
296 }
297
298 pub async fn get_local_user_view_from_jwt_opt(
299   jwt: &Option<String>,
300   pool: &DbPool,
301 ) -> Result<Option<LocalUserView>, LemmyError> {
302   match jwt {
303     Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool).await?)),
304     None => Ok(None),
305   }
306 }
307
308 pub async fn get_local_user_settings_view_from_jwt(
309   jwt: &str,
310   pool: &DbPool,
311 ) -> Result<LocalUserSettingsView, LemmyError> {
312   let claims = Claims::decode(jwt)
313     .map_err(|_| ApiError::err("not_logged_in"))?
314     .claims;
315   let local_user_id = LocalUserId(claims.sub);
316   let local_user_view = blocking(pool, move |conn| {
317     LocalUserSettingsView::read(conn, local_user_id)
318   })
319   .await??;
320   // Check for a site ban
321   if local_user_view.person.banned {
322     return Err(ApiError::err("site_ban").into());
323   }
324
325   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
326
327   Ok(local_user_view)
328 }
329
330 pub async fn get_local_user_settings_view_from_jwt_opt(
331   jwt: &Option<String>,
332   pool: &DbPool,
333 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
334   match jwt {
335     Some(jwt) => Ok(Some(
336       get_local_user_settings_view_from_jwt(jwt, pool).await?,
337     )),
338     None => Ok(None),
339   }
340 }
341
342 pub async fn check_community_ban(
343   person_id: PersonId,
344   community_id: CommunityId,
345   pool: &DbPool,
346 ) -> Result<(), LemmyError> {
347   let is_banned =
348     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
349   if blocking(pool, is_banned).await? {
350     Err(ApiError::err("community_ban").into())
351   } else {
352     Ok(())
353   }
354 }
355
356 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
357   if score == -1 {
358     let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
359     if !site.enable_downvotes {
360       return Err(ApiError::err("downvotes_disabled").into());
361     }
362   }
363   Ok(())
364 }
365
366 /// Returns a list of communities that the user moderates
367 /// or if a community_id is supplied validates the user is a moderator
368 /// of that community and returns the community id in a vec
369 ///
370 /// * `person_id` - the person id of the moderator
371 /// * `community_id` - optional community id to check for moderator privileges
372 /// * `pool` - the diesel db pool
373 pub async fn collect_moderated_communities(
374   person_id: PersonId,
375   community_id: Option<CommunityId>,
376   pool: &DbPool,
377 ) -> Result<Vec<CommunityId>, LemmyError> {
378   if let Some(community_id) = community_id {
379     // if the user provides a community_id, just check for mod/admin privileges
380     is_mod_or_admin(pool, person_id, community_id).await?;
381     Ok(vec![community_id])
382   } else {
383     let ids = blocking(pool, move |conn: &'_ _| {
384       CommunityModerator::get_person_moderated_communities(conn, person_id)
385     })
386     .await??;
387     Ok(ids)
388   }
389 }
390
391 pub async fn build_federated_instances(
392   pool: &DbPool,
393 ) -> Result<Option<FederatedInstances>, LemmyError> {
394   if Settings::get().federation.enabled {
395     let distinct_communities = blocking(pool, move |conn| {
396       Community::distinct_federated_communities(conn)
397     })
398     .await??;
399
400     let allowed = Settings::get().federation.allowed_instances;
401     let blocked = Settings::get().federation.blocked_instances;
402
403     let mut linked = distinct_communities
404       .iter()
405       .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
406       .collect::<Result<Vec<String>, LemmyError>>()?;
407
408     if let Some(allowed) = allowed.as_ref() {
409       linked.extend_from_slice(allowed);
410     }
411
412     if let Some(blocked) = blocked.as_ref() {
413       linked.retain(|a| !blocked.contains(a) && !a.eq(&Settings::get().hostname));
414     }
415
416     // Sort and remove dupes
417     linked.sort_unstable();
418     linked.dedup();
419
420     Ok(Some(FederatedInstances {
421       linked,
422       allowed,
423       blocked,
424     }))
425   } else {
426     Ok(None)
427   }
428 }
429
430 /// Checks the password length
431 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
432   if pass.len() > 60 {
433     Err(ApiError::err("invalid_password").into())
434   } else {
435     Ok(())
436   }
437 }
438
439 /// Checks the site description length
440 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
441   if description.len() > 150 {
442     Err(ApiError::err("site_description_length_overflow").into())
443   } else {
444     Ok(())
445   }
446 }