]> Untitled Git - lemmy.git/blob - crates/api_common/src/lib.rs
Implement instance actor (#1798)
[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 itertools::Itertools;
10 use lemmy_db_schema::{
11   newtypes::{CommunityId, LocalUserId, PersonId, PostId},
12   source::{
13     comment::Comment,
14     community::Community,
15     email_verification::{EmailVerification, EmailVerificationForm},
16     password_reset_request::PasswordResetRequest,
17     person_block::PersonBlock,
18     post::{Post, PostRead, PostReadForm},
19     registration_application::RegistrationApplication,
20     secret::Secret,
21     site::Site,
22   },
23   traits::{ApubActor, Crud, Readable},
24   DbPool,
25 };
26 use lemmy_db_views::{
27   comment_view::CommentQueryBuilder,
28   local_user_view::{LocalUserSettingsView, LocalUserView},
29 };
30 use lemmy_db_views_actor::{
31   community_moderator_view::CommunityModeratorView,
32   community_person_ban_view::CommunityPersonBanView,
33   community_view::CommunityView,
34 };
35 use lemmy_utils::{
36   claims::Claims,
37   email::send_email,
38   settings::structs::{FederationConfig, Settings},
39   utils::generate_random_string,
40   LemmyError,
41   Sensitive,
42 };
43
44 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
45 where
46   F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
47   T: Send + 'static,
48 {
49   let pool = pool.clone();
50   let blocking_span = tracing::info_span!("blocking operation");
51   let res = actix_web::web::block(move || {
52     let entered = blocking_span.enter();
53     let conn = pool.get()?;
54     let res = (f)(&conn);
55     drop(entered);
56     Ok(res) as Result<T, LemmyError>
57   })
58   .await?;
59
60   res
61 }
62
63 #[tracing::instrument(skip_all)]
64 pub async fn is_mod_or_admin(
65   pool: &DbPool,
66   person_id: PersonId,
67   community_id: CommunityId,
68 ) -> Result<(), LemmyError> {
69   let is_mod_or_admin = blocking(pool, move |conn| {
70     CommunityView::is_mod_or_admin(conn, person_id, community_id)
71   })
72   .await?;
73   if !is_mod_or_admin {
74     return Err(LemmyError::from_message("not_a_mod_or_admin"));
75   }
76   Ok(())
77 }
78
79 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
80   if !local_user_view.person.admin {
81     return Err(LemmyError::from_message("not_an_admin"));
82   }
83   Ok(())
84 }
85
86 #[tracing::instrument(skip_all)]
87 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
88   blocking(pool, move |conn| Post::read(conn, post_id))
89     .await?
90     .map_err(LemmyError::from)
91     .map_err(|e| e.with_message("couldnt_find_post"))
92 }
93
94 #[tracing::instrument(skip_all)]
95 pub async fn mark_post_as_read(
96   person_id: PersonId,
97   post_id: PostId,
98   pool: &DbPool,
99 ) -> Result<PostRead, LemmyError> {
100   let post_read_form = PostReadForm { post_id, person_id };
101
102   blocking(pool, move |conn| {
103     PostRead::mark_as_read(conn, &post_read_form)
104   })
105   .await?
106   .map_err(LemmyError::from)
107   .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
108 }
109
110 #[tracing::instrument(skip_all)]
111 pub async fn mark_post_as_unread(
112   person_id: PersonId,
113   post_id: PostId,
114   pool: &DbPool,
115 ) -> Result<usize, LemmyError> {
116   let post_read_form = PostReadForm { post_id, person_id };
117
118   blocking(pool, move |conn| {
119     PostRead::mark_as_unread(conn, &post_read_form)
120   })
121   .await?
122   .map_err(LemmyError::from)
123   .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
124 }
125
126 #[tracing::instrument(skip_all)]
127 pub async fn get_local_user_view_from_jwt(
128   jwt: &str,
129   pool: &DbPool,
130   secret: &Secret,
131 ) -> Result<LocalUserView, LemmyError> {
132   let claims = Claims::decode(jwt, &secret.jwt_secret)
133     .map_err(LemmyError::from)
134     .map_err(|e| e.with_message("not_logged_in"))?
135     .claims;
136   let local_user_id = LocalUserId(claims.sub);
137   let local_user_view =
138     blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
139   // Check for a site ban
140   if local_user_view.person.is_banned() {
141     return Err(LemmyError::from_message("site_ban"));
142   }
143
144   // Check for user deletion
145   if local_user_view.person.deleted {
146     return Err(LemmyError::from_message("deleted"));
147   }
148
149   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
150
151   Ok(local_user_view)
152 }
153
154 /// Checks if user's token was issued before user's password reset.
155 pub fn check_validator_time(
156   validator_time: &chrono::NaiveDateTime,
157   claims: &Claims,
158 ) -> Result<(), LemmyError> {
159   let user_validation_time = validator_time.timestamp();
160   if user_validation_time > claims.iat {
161     Err(LemmyError::from_message("not_logged_in"))
162   } else {
163     Ok(())
164   }
165 }
166
167 #[tracing::instrument(skip_all)]
168 pub async fn get_local_user_view_from_jwt_opt(
169   jwt: Option<&Sensitive<String>>,
170   pool: &DbPool,
171   secret: &Secret,
172 ) -> Result<Option<LocalUserView>, LemmyError> {
173   match jwt {
174     Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
175     None => Ok(None),
176   }
177 }
178
179 #[tracing::instrument(skip_all)]
180 pub async fn get_local_user_settings_view_from_jwt(
181   jwt: &Sensitive<String>,
182   pool: &DbPool,
183   secret: &Secret,
184 ) -> Result<LocalUserSettingsView, LemmyError> {
185   let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
186     .map_err(LemmyError::from)
187     .map_err(|e| e.with_message("not_logged_in"))?
188     .claims;
189   let local_user_id = LocalUserId(claims.sub);
190   let local_user_view = blocking(pool, move |conn| {
191     LocalUserSettingsView::read(conn, local_user_id)
192   })
193   .await??;
194   // Check for a site ban
195   if local_user_view.person.is_banned() {
196     return Err(LemmyError::from_message("site_ban"));
197   }
198
199   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
200
201   Ok(local_user_view)
202 }
203
204 #[tracing::instrument(skip_all)]
205 pub async fn get_local_user_settings_view_from_jwt_opt(
206   jwt: Option<&Sensitive<String>>,
207   pool: &DbPool,
208   secret: &Secret,
209 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
210   match jwt {
211     Some(jwt) => Ok(Some(
212       get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
213     )),
214     None => Ok(None),
215   }
216 }
217
218 #[tracing::instrument(skip_all)]
219 pub async fn check_community_ban(
220   person_id: PersonId,
221   community_id: CommunityId,
222   pool: &DbPool,
223 ) -> Result<(), LemmyError> {
224   let is_banned =
225     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
226   if blocking(pool, is_banned).await? {
227     Err(LemmyError::from_message("community_ban"))
228   } else {
229     Ok(())
230   }
231 }
232
233 #[tracing::instrument(skip_all)]
234 pub async fn check_community_deleted_or_removed(
235   community_id: CommunityId,
236   pool: &DbPool,
237 ) -> Result<(), LemmyError> {
238   let community = blocking(pool, move |conn| Community::read(conn, community_id))
239     .await?
240     .map_err(LemmyError::from)
241     .map_err(|e| e.with_message("couldnt_find_community"))?;
242   if community.deleted || community.removed {
243     Err(LemmyError::from_message("deleted"))
244   } else {
245     Ok(())
246   }
247 }
248
249 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
250   if post.deleted || post.removed {
251     Err(LemmyError::from_message("deleted"))
252   } else {
253     Ok(())
254   }
255 }
256
257 #[tracing::instrument(skip_all)]
258 pub async fn check_person_block(
259   my_id: PersonId,
260   potential_blocker_id: PersonId,
261   pool: &DbPool,
262 ) -> Result<(), LemmyError> {
263   let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
264   if blocking(pool, is_blocked).await? {
265     Err(LemmyError::from_message("person_block"))
266   } else {
267     Ok(())
268   }
269 }
270
271 #[tracing::instrument(skip_all)]
272 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
273   if score == -1 {
274     let site = blocking(pool, Site::read_local_site).await??;
275     if !site.enable_downvotes {
276       return Err(LemmyError::from_message("downvotes_disabled"));
277     }
278   }
279   Ok(())
280 }
281
282 #[tracing::instrument(skip_all)]
283 pub async fn check_private_instance(
284   local_user_view: &Option<LocalUserView>,
285   pool: &DbPool,
286 ) -> Result<(), LemmyError> {
287   if local_user_view.is_none() {
288     let site = blocking(pool, Site::read_local_site).await?;
289
290     // The site might not be set up yet
291     if let Ok(site) = site {
292       if site.private_instance {
293         return Err(LemmyError::from_message("instance_is_private"));
294       }
295     }
296   }
297   Ok(())
298 }
299
300 #[tracing::instrument(skip_all)]
301 pub async fn build_federated_instances(
302   pool: &DbPool,
303   federation_config: &FederationConfig,
304   hostname: &str,
305 ) -> Result<Option<FederatedInstances>, LemmyError> {
306   let federation = federation_config.to_owned();
307   if federation.enabled {
308     let distinct_communities = blocking(pool, move |conn| {
309       Community::distinct_federated_communities(conn)
310     })
311     .await??;
312
313     let allowed = federation.allowed_instances;
314     let blocked = federation.blocked_instances;
315
316     let mut linked = distinct_communities
317       .iter()
318       .map(|actor_id| Ok(actor_id.host_str().unwrap_or("").to_string()))
319       .collect::<Result<Vec<String>, LemmyError>>()?;
320
321     if let Some(allowed) = allowed.as_ref() {
322       linked.extend_from_slice(allowed);
323     }
324
325     if let Some(blocked) = blocked.as_ref() {
326       linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
327     }
328
329     // Sort and remove dupes
330     linked.sort_unstable();
331     linked.dedup();
332
333     Ok(Some(FederatedInstances {
334       linked,
335       allowed,
336       blocked,
337     }))
338   } else {
339     Ok(None)
340   }
341 }
342
343 /// Checks the password length
344 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
345   if !(10..=60).contains(&pass.len()) {
346     Err(LemmyError::from_message("invalid_password"))
347   } else {
348     Ok(())
349   }
350 }
351
352 /// Checks the site description length
353 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
354   if description.len() > 150 {
355     Err(LemmyError::from_message("site_description_length_overflow"))
356   } else {
357     Ok(())
358   }
359 }
360
361 /// Checks for a honeypot. If this field is filled, fail the rest of the function
362 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
363   if honeypot.is_some() {
364     Err(LemmyError::from_message("honeypot_fail"))
365   } else {
366     Ok(())
367   }
368 }
369
370 pub fn send_email_to_user(
371   local_user_view: &LocalUserView,
372   subject_text: &str,
373   body_text: &str,
374   comment_content: &str,
375   settings: &Settings,
376 ) {
377   if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
378     return;
379   }
380
381   if let Some(user_email) = &local_user_view.local_user.email {
382     let subject = &format!(
383       "{} - {} {}",
384       subject_text, settings.hostname, local_user_view.person.name,
385     );
386     let html = &format!(
387       "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
388       body_text,
389       local_user_view.person.name,
390       comment_content,
391       settings.get_protocol_and_hostname()
392     );
393     match send_email(
394       subject,
395       user_email,
396       &local_user_view.person.name,
397       html,
398       settings,
399     ) {
400       Ok(_o) => _o,
401       Err(e) => tracing::error!("{}", e),
402     };
403   }
404 }
405
406 pub async fn send_password_reset_email(
407   local_user_view: &LocalUserView,
408   pool: &DbPool,
409   settings: &Settings,
410 ) -> Result<(), LemmyError> {
411   // Generate a random token
412   let token = generate_random_string();
413
414   // Insert the row
415   let token2 = token.clone();
416   let local_user_id = local_user_view.local_user.id;
417   blocking(pool, move |conn| {
418     PasswordResetRequest::create_token(conn, local_user_id, &token2)
419   })
420   .await??;
421
422   let email = &local_user_view.local_user.email.to_owned().expect("email");
423   let subject = &format!("Password reset for {}", local_user_view.person.name);
424   let protocol_and_hostname = settings.get_protocol_and_hostname();
425   let html = &format!("<h1>Password Reset Request for {}</h1><br><a href={}/password_change/{}>Click here to reset your password</a>", local_user_view.person.name, protocol_and_hostname, &token);
426   send_email(subject, email, &local_user_view.person.name, html, settings)
427 }
428
429 /// Send a verification email
430 pub async fn send_verification_email(
431   local_user_id: LocalUserId,
432   new_email: &str,
433   username: &str,
434   pool: &DbPool,
435   settings: &Settings,
436 ) -> Result<(), LemmyError> {
437   let form = EmailVerificationForm {
438     local_user_id,
439     email: new_email.to_string(),
440     verification_token: generate_random_string(),
441   };
442   let verify_link = format!(
443     "{}/verify_email/{}",
444     settings.get_protocol_and_hostname(),
445     &form.verification_token
446   );
447   blocking(pool, move |conn| EmailVerification::create(conn, &form)).await??;
448
449   let subject = format!("Verify your email address for {}", settings.hostname);
450   let body = format!(
451     concat!(
452       "Please click the link below to verify your email address ",
453       "for the account @{}@{}. Ignore this email if the account isn't yours.<br><br>",
454       "<a href=\"{}\">Verify your email</a>"
455     ),
456     username, settings.hostname, verify_link
457   );
458   send_email(&subject, new_email, username, &body, settings)?;
459
460   Ok(())
461 }
462
463 pub fn send_email_verification_success(
464   local_user_view: &LocalUserView,
465   settings: &Settings,
466 ) -> Result<(), LemmyError> {
467   let email = &local_user_view.local_user.email.to_owned().expect("email");
468   let subject = &format!("Email verified for {}", local_user_view.person.actor_id);
469   let html = "Your email has been verified.";
470   send_email(subject, email, &local_user_view.person.name, html, settings)
471 }
472
473 pub fn send_application_approved_email(
474   local_user_view: &LocalUserView,
475   settings: &Settings,
476 ) -> Result<(), LemmyError> {
477   let email = &local_user_view.local_user.email.to_owned().expect("email");
478   let subject = &format!(
479     "Registration approved for {}",
480     local_user_view.person.actor_id
481   );
482   let html = &format!(
483     "Your registration application has been approved. Welcome to {}!",
484     settings.hostname
485   );
486   send_email(subject, email, &local_user_view.person.name, html, settings)
487 }
488
489 pub async fn check_registration_application(
490   site: &Site,
491   local_user_view: &LocalUserView,
492   pool: &DbPool,
493 ) -> Result<(), LemmyError> {
494   if site.require_application
495     && !local_user_view.local_user.accepted_application
496     && !local_user_view.person.admin
497   {
498     // Fetch the registration, see if its denied
499     let local_user_id = local_user_view.local_user.id;
500     let registration = blocking(pool, move |conn| {
501       RegistrationApplication::find_by_local_user_id(conn, local_user_id)
502     })
503     .await??;
504     if registration.deny_reason.is_some() {
505       return Err(LemmyError::from_message("registration_denied"));
506     } else {
507       return Err(LemmyError::from_message("registration_application_pending"));
508     }
509   }
510   Ok(())
511 }
512
513 /// TODO this check should be removed after https://github.com/LemmyNet/lemmy/issues/868 is done.
514 pub async fn check_private_instance_and_federation_enabled(
515   pool: &DbPool,
516   settings: &Settings,
517 ) -> Result<(), LemmyError> {
518   let site_opt = blocking(pool, Site::read_local_site).await?;
519
520   if let Ok(site) = site_opt {
521     if site.private_instance && settings.federation.enabled {
522       return Err(LemmyError::from_message(
523         "Cannot have both private instance and federation enabled.",
524       ));
525     }
526   }
527   Ok(())
528 }
529
530 /// Resolve actor identifier (eg `!news@example.com`) from local database to avoid network requests.
531 /// This only works for local actors, and remote actors which were previously fetched (so it doesnt
532 /// trigger any new fetch).
533 #[tracing::instrument(skip_all)]
534 pub async fn resolve_actor_identifier<Actor>(
535   identifier: &str,
536   pool: &DbPool,
537 ) -> Result<Actor, LemmyError>
538 where
539   Actor: ApubActor + Send + 'static,
540 {
541   // remote actor
542   if identifier.contains('@') {
543     let (name, domain) = identifier
544       .splitn(2, '@')
545       .collect_tuple()
546       .expect("invalid query");
547     let name = name.to_string();
548     let domain = format!("{}://{}", Settings::get().get_protocol_string(), domain);
549     Ok(
550       blocking(pool, move |conn| {
551         Actor::read_from_name_and_domain(conn, &name, &domain)
552       })
553       .await??,
554     )
555   }
556   // local actor
557   else {
558     let identifier = identifier.to_string();
559     Ok(blocking(pool, move |conn| Actor::read_from_name(conn, &identifier)).await??)
560   }
561 }
562
563 pub async fn remove_user_data(banned_person_id: PersonId, pool: &DbPool) -> Result<(), LemmyError> {
564   // Posts
565   blocking(pool, move |conn: &'_ _| {
566     Post::update_removed_for_creator(conn, banned_person_id, None, true)
567   })
568   .await??;
569
570   // Communities
571   // Remove all communities where they're the top mod
572   // for now, remove the communities manually
573   let first_mod_communities = blocking(pool, move |conn: &'_ _| {
574     CommunityModeratorView::get_community_first_mods(conn)
575   })
576   .await??;
577
578   // Filter to only this banned users top communities
579   let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
580     .into_iter()
581     .filter(|fmc| fmc.moderator.id == banned_person_id)
582     .collect();
583
584   for first_mod_community in banned_user_first_communities {
585     blocking(pool, move |conn: &'_ _| {
586       Community::update_removed(conn, first_mod_community.community.id, true)
587     })
588     .await??;
589   }
590
591   // Comments
592   blocking(pool, move |conn: &'_ _| {
593     Comment::update_removed_for_creator(conn, banned_person_id, true)
594   })
595   .await??;
596
597   Ok(())
598 }
599
600 pub async fn remove_user_data_in_community(
601   community_id: CommunityId,
602   banned_person_id: PersonId,
603   pool: &DbPool,
604 ) -> Result<(), LemmyError> {
605   // Posts
606   blocking(pool, move |conn| {
607     Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
608   })
609   .await??;
610
611   // Comments
612   // TODO Diesel doesn't allow updates with joins, so this has to be a loop
613   let comments = blocking(pool, move |conn| {
614     CommentQueryBuilder::create(conn)
615       .creator_id(banned_person_id)
616       .community_id(community_id)
617       .limit(std::i64::MAX)
618       .list()
619   })
620   .await??;
621
622   for comment_view in &comments {
623     let comment_id = comment_view.comment.id;
624     blocking(pool, move |conn| {
625       Comment::update_removed(conn, comment_id, true)
626     })
627     .await??;
628   }
629
630   Ok(())
631 }