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