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