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