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