]> Untitled Git - lemmy.git/blob - crates/api_common/src/utils.rs
Dont return error in case optional auth is invalid (#2879)
[lemmy.git] / crates / api_common / src / utils.rs
1 use crate::{
2   context::LemmyContext,
3   request::purge_image_from_pictrs,
4   sensitive::Sensitive,
5   site::FederatedInstances,
6 };
7 use anyhow::Context;
8 use chrono::NaiveDateTime;
9 use futures::try_join;
10 use lemmy_db_schema::{
11   impls::person::is_banned,
12   newtypes::{CommunityId, DbUrl, LocalUserId, PersonId, PostId},
13   source::{
14     comment::{Comment, CommentUpdateForm},
15     community::{Community, CommunityModerator, CommunityUpdateForm},
16     email_verification::{EmailVerification, EmailVerificationForm},
17     instance::Instance,
18     local_site::LocalSite,
19     local_site_rate_limit::LocalSiteRateLimit,
20     password_reset_request::PasswordResetRequest,
21     person::{Person, PersonUpdateForm},
22     person_block::PersonBlock,
23     post::{Post, PostRead, PostReadForm},
24     registration_application::RegistrationApplication,
25   },
26   traits::{Crud, Readable},
27   utils::DbPool,
28   RegistrationMode,
29 };
30 use lemmy_db_views::{comment_view::CommentQuery, structs::LocalUserView};
31 use lemmy_db_views_actor::structs::{
32   CommunityModeratorView,
33   CommunityPersonBanView,
34   CommunityView,
35   PersonView,
36 };
37 use lemmy_utils::{
38   claims::Claims,
39   email::{send_email, translations::Lang},
40   error::LemmyError,
41   location_info,
42   rate_limit::RateLimitConfig,
43   settings::structs::Settings,
44   utils::slurs::build_slur_regex,
45 };
46 use regex::Regex;
47 use reqwest_middleware::ClientWithMiddleware;
48 use rosetta_i18n::{Language, LanguageId};
49 use tracing::warn;
50 use url::{ParseError, Url};
51
52 #[tracing::instrument(skip_all)]
53 pub async fn is_mod_or_admin(
54   pool: &DbPool,
55   person_id: PersonId,
56   community_id: CommunityId,
57 ) -> Result<(), LemmyError> {
58   let is_mod_or_admin = CommunityView::is_mod_or_admin(pool, person_id, community_id).await?;
59   if !is_mod_or_admin {
60     return Err(LemmyError::from_message("not_a_mod_or_admin"));
61   }
62   Ok(())
63 }
64
65 #[tracing::instrument(skip_all)]
66 pub async fn is_mod_or_admin_opt(
67   pool: &DbPool,
68   local_user_view: Option<&LocalUserView>,
69   community_id: Option<CommunityId>,
70 ) -> Result<(), LemmyError> {
71   if let Some(local_user_view) = local_user_view {
72     if let Some(community_id) = community_id {
73       is_mod_or_admin(pool, local_user_view.person.id, community_id).await
74     } else {
75       is_admin(local_user_view)
76     }
77   } else {
78     Err(LemmyError::from_message("not_a_mod_or_admin"))
79   }
80 }
81
82 pub async fn is_top_admin(pool: &DbPool, person_id: PersonId) -> Result<(), LemmyError> {
83   let admins = PersonView::admins(pool).await?;
84   let top_admin = admins
85     .first()
86     .ok_or_else(|| LemmyError::from_message("no admins"))?;
87
88   if top_admin.person.id != person_id {
89     return Err(LemmyError::from_message("not_top_admin"));
90   }
91   Ok(())
92 }
93
94 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
95   if !local_user_view.person.admin {
96     return Err(LemmyError::from_message("not_an_admin"));
97   }
98   Ok(())
99 }
100
101 pub fn is_top_mod(
102   local_user_view: &LocalUserView,
103   community_mods: &[CommunityModeratorView],
104 ) -> Result<(), LemmyError> {
105   if local_user_view.person.id
106     != community_mods
107       .first()
108       .map(|cm| cm.moderator.id)
109       .unwrap_or(PersonId(0))
110   {
111     return Err(LemmyError::from_message("not_top_mod"));
112   }
113   Ok(())
114 }
115
116 #[tracing::instrument(skip_all)]
117 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
118   Post::read(pool, post_id)
119     .await
120     .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))
121 }
122
123 #[tracing::instrument(skip_all)]
124 pub async fn mark_post_as_read(
125   person_id: PersonId,
126   post_id: PostId,
127   pool: &DbPool,
128 ) -> Result<PostRead, LemmyError> {
129   let post_read_form = PostReadForm { post_id, person_id };
130
131   PostRead::mark_as_read(pool, &post_read_form)
132     .await
133     .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
134 }
135
136 #[tracing::instrument(skip_all)]
137 pub async fn mark_post_as_unread(
138   person_id: PersonId,
139   post_id: PostId,
140   pool: &DbPool,
141 ) -> Result<usize, LemmyError> {
142   let post_read_form = PostReadForm { post_id, person_id };
143
144   PostRead::mark_as_unread(pool, &post_read_form)
145     .await
146     .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
147 }
148
149 #[tracing::instrument(skip_all)]
150 pub async fn local_user_view_from_jwt(
151   jwt: &str,
152   context: &LemmyContext,
153 ) -> Result<LocalUserView, LemmyError> {
154   let claims = Claims::decode(jwt, &context.secret().jwt_secret)
155     .map_err(|e| e.with_message("not_logged_in"))?
156     .claims;
157   let local_user_id = LocalUserId(claims.sub);
158   let local_user_view = LocalUserView::read(context.pool(), local_user_id).await?;
159   check_user_valid(
160     local_user_view.person.banned,
161     local_user_view.person.ban_expires,
162     local_user_view.person.deleted,
163   )?;
164
165   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
166
167   Ok(local_user_view)
168 }
169
170 #[tracing::instrument(skip_all)]
171 pub async fn local_user_view_from_jwt_opt(
172   jwt: Option<&Sensitive<String>>,
173   context: &LemmyContext,
174 ) -> Option<LocalUserView> {
175   local_user_view_from_jwt(jwt?, context).await.ok()
176 }
177
178 /// Checks if user's token was issued before user's password reset.
179 pub fn check_validator_time(
180   validator_time: &NaiveDateTime,
181   claims: &Claims,
182 ) -> Result<(), LemmyError> {
183   let user_validation_time = validator_time.timestamp();
184   if user_validation_time > claims.iat {
185     Err(LemmyError::from_message("not_logged_in"))
186   } else {
187     Ok(())
188   }
189 }
190
191 pub fn check_user_valid(
192   banned: bool,
193   ban_expires: Option<NaiveDateTime>,
194   deleted: bool,
195 ) -> Result<(), LemmyError> {
196   // Check for a site ban
197   if is_banned(banned, ban_expires) {
198     return Err(LemmyError::from_message("site_ban"));
199   }
200
201   // check for account deletion
202   if deleted {
203     return Err(LemmyError::from_message("deleted"));
204   }
205
206   Ok(())
207 }
208
209 #[tracing::instrument(skip_all)]
210 pub async fn check_community_ban(
211   person_id: PersonId,
212   community_id: CommunityId,
213   pool: &DbPool,
214 ) -> Result<(), LemmyError> {
215   let is_banned = CommunityPersonBanView::get(pool, person_id, community_id)
216     .await
217     .is_ok();
218   if is_banned {
219     Err(LemmyError::from_message("community_ban"))
220   } else {
221     Ok(())
222   }
223 }
224
225 #[tracing::instrument(skip_all)]
226 pub async fn check_community_deleted_or_removed(
227   community_id: CommunityId,
228   pool: &DbPool,
229 ) -> Result<(), LemmyError> {
230   let community = Community::read(pool, community_id)
231     .await
232     .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
233   if community.deleted || community.removed {
234     Err(LemmyError::from_message("deleted"))
235   } else {
236     Ok(())
237   }
238 }
239
240 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
241   if post.deleted || post.removed {
242     Err(LemmyError::from_message("deleted"))
243   } else {
244     Ok(())
245   }
246 }
247
248 #[tracing::instrument(skip_all)]
249 pub async fn check_person_block(
250   my_id: PersonId,
251   potential_blocker_id: PersonId,
252   pool: &DbPool,
253 ) -> Result<(), LemmyError> {
254   let is_blocked = PersonBlock::read(pool, potential_blocker_id, my_id)
255     .await
256     .is_ok();
257   if is_blocked {
258     Err(LemmyError::from_message("person_block"))
259   } else {
260     Ok(())
261   }
262 }
263
264 #[tracing::instrument(skip_all)]
265 pub fn check_downvotes_enabled(score: i16, local_site: &LocalSite) -> Result<(), LemmyError> {
266   if score == -1 && !local_site.enable_downvotes {
267     return Err(LemmyError::from_message("downvotes_disabled"));
268   }
269   Ok(())
270 }
271
272 #[tracing::instrument(skip_all)]
273 pub fn check_private_instance(
274   local_user_view: &Option<LocalUserView>,
275   local_site: &LocalSite,
276 ) -> Result<(), LemmyError> {
277   if local_user_view.is_none() && local_site.private_instance {
278     return Err(LemmyError::from_message("instance_is_private"));
279   }
280   Ok(())
281 }
282
283 #[tracing::instrument(skip_all)]
284 pub async fn build_federated_instances(
285   local_site: &LocalSite,
286   pool: &DbPool,
287 ) -> Result<Option<FederatedInstances>, LemmyError> {
288   if local_site.federation_enabled {
289     // TODO I hate that this requires 3 queries
290     let (linked, allowed, blocked) = try_join!(
291       Instance::linked(pool),
292       Instance::allowlist(pool),
293       Instance::blocklist(pool)
294     )?;
295
296     Ok(Some(FederatedInstances {
297       linked,
298       allowed,
299       blocked,
300     }))
301   } else {
302     Ok(None)
303   }
304 }
305
306 /// Checks the password length
307 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
308   if !(10..=60).contains(&pass.chars().count()) {
309     Err(LemmyError::from_message("invalid_password"))
310   } else {
311     Ok(())
312   }
313 }
314
315 /// Checks the site description length
316 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
317   if description.len() > 150 {
318     Err(LemmyError::from_message("site_description_length_overflow"))
319   } else {
320     Ok(())
321   }
322 }
323
324 /// Checks for a honeypot. If this field is filled, fail the rest of the function
325 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
326   if honeypot.is_some() && honeypot != &Some(String::new()) {
327     Err(LemmyError::from_message("honeypot_fail"))
328   } else {
329     Ok(())
330   }
331 }
332
333 pub fn send_email_to_user(
334   local_user_view: &LocalUserView,
335   subject: &str,
336   body: &str,
337   settings: &Settings,
338 ) {
339   if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
340     return;
341   }
342
343   if let Some(user_email) = &local_user_view.local_user.email {
344     match send_email(
345       subject,
346       user_email,
347       &local_user_view.person.name,
348       body,
349       settings,
350     ) {
351       Ok(_o) => _o,
352       Err(e) => warn!("{}", e),
353     };
354   }
355 }
356
357 pub async fn send_password_reset_email(
358   user: &LocalUserView,
359   pool: &DbPool,
360   settings: &Settings,
361 ) -> Result<(), LemmyError> {
362   // Generate a random token
363   let token = uuid::Uuid::new_v4().to_string();
364
365   // Insert the row
366   let token2 = token.clone();
367   let local_user_id = user.local_user.id;
368   PasswordResetRequest::create_token(pool, local_user_id, &token2).await?;
369
370   let email = &user.local_user.email.clone().expect("email");
371   let lang = get_interface_language(user);
372   let subject = &lang.password_reset_subject(&user.person.name);
373   let protocol_and_hostname = settings.get_protocol_and_hostname();
374   let reset_link = format!("{}/password_change/{}", protocol_and_hostname, &token);
375   let body = &lang.password_reset_body(reset_link, &user.person.name);
376   send_email(subject, email, &user.person.name, body, settings)
377 }
378
379 /// Send a verification email
380 pub async fn send_verification_email(
381   user: &LocalUserView,
382   new_email: &str,
383   pool: &DbPool,
384   settings: &Settings,
385 ) -> Result<(), LemmyError> {
386   let form = EmailVerificationForm {
387     local_user_id: user.local_user.id,
388     email: new_email.to_string(),
389     verification_token: uuid::Uuid::new_v4().to_string(),
390   };
391   let verify_link = format!(
392     "{}/verify_email/{}",
393     settings.get_protocol_and_hostname(),
394     &form.verification_token
395   );
396   EmailVerification::create(pool, &form).await?;
397
398   let lang = get_interface_language(user);
399   let subject = lang.verify_email_subject(&settings.hostname);
400   let body = lang.verify_email_body(&settings.hostname, &user.person.name, verify_link);
401   send_email(&subject, new_email, &user.person.name, &body, settings)?;
402
403   Ok(())
404 }
405
406 pub fn send_email_verification_success(
407   user: &LocalUserView,
408   settings: &Settings,
409 ) -> Result<(), LemmyError> {
410   let email = &user.local_user.email.clone().expect("email");
411   let lang = get_interface_language(user);
412   let subject = &lang.email_verified_subject(&user.person.actor_id);
413   let body = &lang.email_verified_body();
414   send_email(subject, email, &user.person.name, body, settings)
415 }
416
417 pub fn get_interface_language(user: &LocalUserView) -> Lang {
418   lang_str_to_lang(&user.local_user.interface_language)
419 }
420
421 pub fn get_interface_language_from_settings(user: &LocalUserView) -> Lang {
422   lang_str_to_lang(&user.local_user.interface_language)
423 }
424
425 fn lang_str_to_lang(lang: &str) -> Lang {
426   let lang_id = LanguageId::new(lang);
427   Lang::from_language_id(&lang_id).unwrap_or_else(|| {
428     let en = LanguageId::new("en");
429     Lang::from_language_id(&en).expect("default language")
430   })
431 }
432
433 pub fn local_site_rate_limit_to_rate_limit_config(
434   local_site_rate_limit: &LocalSiteRateLimit,
435 ) -> RateLimitConfig {
436   let l = local_site_rate_limit;
437   RateLimitConfig {
438     message: l.message,
439     message_per_second: l.message_per_second,
440     post: l.post,
441     post_per_second: l.post_per_second,
442     register: l.register,
443     register_per_second: l.register_per_second,
444     image: l.image,
445     image_per_second: l.image_per_second,
446     comment: l.comment,
447     comment_per_second: l.comment_per_second,
448     search: l.search,
449     search_per_second: l.search_per_second,
450   }
451 }
452
453 pub fn local_site_to_slur_regex(local_site: &LocalSite) -> Option<Regex> {
454   build_slur_regex(local_site.slur_filter_regex.as_deref())
455 }
456
457 pub fn local_site_opt_to_slur_regex(local_site: &Option<LocalSite>) -> Option<Regex> {
458   local_site
459     .as_ref()
460     .map(local_site_to_slur_regex)
461     .unwrap_or(None)
462 }
463
464 pub fn send_application_approved_email(
465   user: &LocalUserView,
466   settings: &Settings,
467 ) -> Result<(), LemmyError> {
468   let email = &user.local_user.email.clone().expect("email");
469   let lang = get_interface_language(user);
470   let subject = lang.registration_approved_subject(&user.person.actor_id);
471   let body = lang.registration_approved_body(&settings.hostname);
472   send_email(&subject, email, &user.person.name, &body, settings)
473 }
474
475 /// Send a new applicant email notification to all admins
476 pub async fn send_new_applicant_email_to_admins(
477   applicant_username: &str,
478   pool: &DbPool,
479   settings: &Settings,
480 ) -> Result<(), LemmyError> {
481   // Collect the admins with emails
482   let admins = LocalUserView::list_admins_with_emails(pool).await?;
483
484   let applications_link = &format!(
485     "{}/registration_applications",
486     settings.get_protocol_and_hostname(),
487   );
488
489   for admin in &admins {
490     let email = &admin.local_user.email.clone().expect("email");
491     let lang = get_interface_language_from_settings(admin);
492     let subject = lang.new_application_subject(&settings.hostname, applicant_username);
493     let body = lang.new_application_body(applications_link);
494     send_email(&subject, email, &admin.person.name, &body, settings)?;
495   }
496   Ok(())
497 }
498
499 /// Send a report to all admins
500 pub async fn send_new_report_email_to_admins(
501   reporter_username: &str,
502   reported_username: &str,
503   pool: &DbPool,
504   settings: &Settings,
505 ) -> Result<(), LemmyError> {
506   // Collect the admins with emails
507   let admins = LocalUserView::list_admins_with_emails(pool).await?;
508
509   let reports_link = &format!("{}/reports", settings.get_protocol_and_hostname(),);
510
511   for admin in &admins {
512     let email = &admin.local_user.email.clone().expect("email");
513     let lang = get_interface_language_from_settings(admin);
514     let subject = lang.new_report_subject(&settings.hostname, reporter_username, reported_username);
515     let body = lang.new_report_body(reports_link);
516     send_email(&subject, email, &admin.person.name, &body, settings)?;
517   }
518   Ok(())
519 }
520
521 pub async fn check_registration_application(
522   local_user_view: &LocalUserView,
523   local_site: &LocalSite,
524   pool: &DbPool,
525 ) -> Result<(), LemmyError> {
526   if local_site.registration_mode == RegistrationMode::RequireApplication
527     && !local_user_view.local_user.accepted_application
528     && !local_user_view.person.admin
529   {
530     // Fetch the registration, see if its denied
531     let local_user_id = local_user_view.local_user.id;
532     let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?;
533     if let Some(deny_reason) = registration.deny_reason {
534       let lang = get_interface_language(local_user_view);
535       let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason);
536       return Err(LemmyError::from_message(&registration_denied_message));
537     } else {
538       return Err(LemmyError::from_message("registration_application_pending"));
539     }
540   }
541   Ok(())
542 }
543
544 pub fn check_private_instance_and_federation_enabled(
545   local_site: &LocalSite,
546 ) -> Result<(), LemmyError> {
547   if local_site.private_instance && local_site.federation_enabled {
548     return Err(LemmyError::from_message(
549       "Cannot have both private instance and federation enabled.",
550     ));
551   }
552   Ok(())
553 }
554
555 pub async fn purge_image_posts_for_person(
556   banned_person_id: PersonId,
557   pool: &DbPool,
558   settings: &Settings,
559   client: &ClientWithMiddleware,
560 ) -> Result<(), LemmyError> {
561   let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
562   for post in posts {
563     if let Some(url) = post.url {
564       purge_image_from_pictrs(client, settings, &url).await.ok();
565     }
566     if let Some(thumbnail_url) = post.thumbnail_url {
567       purge_image_from_pictrs(client, settings, &thumbnail_url)
568         .await
569         .ok();
570     }
571   }
572
573   Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
574
575   Ok(())
576 }
577
578 pub async fn purge_image_posts_for_community(
579   banned_community_id: CommunityId,
580   pool: &DbPool,
581   settings: &Settings,
582   client: &ClientWithMiddleware,
583 ) -> Result<(), LemmyError> {
584   let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?;
585   for post in posts {
586     if let Some(url) = post.url {
587       purge_image_from_pictrs(client, settings, &url).await.ok();
588     }
589     if let Some(thumbnail_url) = post.thumbnail_url {
590       purge_image_from_pictrs(client, settings, &thumbnail_url)
591         .await
592         .ok();
593     }
594   }
595
596   Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?;
597
598   Ok(())
599 }
600
601 pub async fn remove_user_data(
602   banned_person_id: PersonId,
603   pool: &DbPool,
604   settings: &Settings,
605   client: &ClientWithMiddleware,
606 ) -> Result<(), LemmyError> {
607   // Purge user images
608   let person = Person::read(pool, banned_person_id).await?;
609   if let Some(avatar) = person.avatar {
610     purge_image_from_pictrs(client, settings, &avatar)
611       .await
612       .ok();
613   }
614   if let Some(banner) = person.banner {
615     purge_image_from_pictrs(client, settings, &banner)
616       .await
617       .ok();
618   }
619
620   // Update the fields to None
621   Person::update(
622     pool,
623     banned_person_id,
624     &PersonUpdateForm::builder()
625       .avatar(Some(None))
626       .banner(Some(None))
627       .build(),
628   )
629   .await?;
630
631   // Posts
632   Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
633
634   // Purge image posts
635   purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
636
637   // Communities
638   // Remove all communities where they're the top mod
639   // for now, remove the communities manually
640   let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
641
642   // Filter to only this banned users top communities
643   let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
644     .into_iter()
645     .filter(|fmc| fmc.moderator.id == banned_person_id)
646     .collect();
647
648   for first_mod_community in banned_user_first_communities {
649     let community_id = first_mod_community.community.id;
650     Community::update(
651       pool,
652       community_id,
653       &CommunityUpdateForm::builder().removed(Some(true)).build(),
654     )
655     .await?;
656
657     // Delete the community images
658     if let Some(icon) = first_mod_community.community.icon {
659       purge_image_from_pictrs(client, settings, &icon).await.ok();
660     }
661     if let Some(banner) = first_mod_community.community.banner {
662       purge_image_from_pictrs(client, settings, &banner)
663         .await
664         .ok();
665     }
666     // Update the fields to None
667     Community::update(
668       pool,
669       community_id,
670       &CommunityUpdateForm::builder()
671         .icon(Some(None))
672         .banner(Some(None))
673         .build(),
674     )
675     .await?;
676   }
677
678   // Comments
679   Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
680
681   Ok(())
682 }
683
684 pub async fn remove_user_data_in_community(
685   community_id: CommunityId,
686   banned_person_id: PersonId,
687   pool: &DbPool,
688 ) -> Result<(), LemmyError> {
689   // Posts
690   Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
691
692   // Comments
693   // TODO Diesel doesn't allow updates with joins, so this has to be a loop
694   let comments = CommentQuery::builder()
695     .pool(pool)
696     .creator_id(Some(banned_person_id))
697     .community_id(Some(community_id))
698     .limit(Some(i64::MAX))
699     .build()
700     .list()
701     .await?;
702
703   for comment_view in &comments {
704     let comment_id = comment_view.comment.id;
705     Comment::update(
706       pool,
707       comment_id,
708       &CommentUpdateForm::builder().removed(Some(true)).build(),
709     )
710     .await?;
711   }
712
713   Ok(())
714 }
715
716 pub async fn delete_user_account(
717   person_id: PersonId,
718   pool: &DbPool,
719   settings: &Settings,
720   client: &ClientWithMiddleware,
721 ) -> Result<(), LemmyError> {
722   // Delete their images
723   let person = Person::read(pool, person_id).await?;
724   if let Some(avatar) = person.avatar {
725     purge_image_from_pictrs(client, settings, &avatar)
726       .await
727       .ok();
728   }
729   if let Some(banner) = person.banner {
730     purge_image_from_pictrs(client, settings, &banner)
731       .await
732       .ok();
733   }
734   // No need to update avatar and banner, those are handled in Person::delete_account
735
736   // Comments
737   Comment::permadelete_for_creator(pool, person_id)
738     .await
739     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
740
741   // Posts
742   Post::permadelete_for_creator(pool, person_id)
743     .await
744     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
745
746   // Purge image posts
747   purge_image_posts_for_person(person_id, pool, settings, client).await?;
748
749   // Leave communities they mod
750   CommunityModerator::leave_all_communities(pool, person_id).await?;
751
752   Person::delete_account(pool, person_id).await?;
753
754   Ok(())
755 }
756
757 #[cfg(test)]
758 mod tests {
759   use crate::utils::{honeypot_check, password_length_check};
760
761   #[test]
762   #[rustfmt::skip]
763   fn password_length() {
764     assert!(password_length_check("Õ¼¾°3yË,o¸ãtÌÈú|ÇÁÙAøüÒI©·¤(T]/ð>æºWæ[C¤bªWöaÃÎñ·{=û³&§½K/c").is_ok());
765     assert!(password_length_check("1234567890").is_ok());
766     assert!(password_length_check("short").is_err());
767     assert!(password_length_check("looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong").is_err());
768   }
769
770   #[test]
771   fn honeypot() {
772     assert!(honeypot_check(&None).is_ok());
773     assert!(honeypot_check(&Some(String::new())).is_ok());
774     assert!(honeypot_check(&Some("1".to_string())).is_err());
775     assert!(honeypot_check(&Some("message".to_string())).is_err());
776   }
777 }
778
779 pub enum EndpointType {
780   Community,
781   Person,
782   Post,
783   Comment,
784   PrivateMessage,
785 }
786
787 /// Generates an apub endpoint for a given domain, IE xyz.tld
788 pub fn generate_local_apub_endpoint(
789   endpoint_type: EndpointType,
790   name: &str,
791   domain: &str,
792 ) -> Result<DbUrl, ParseError> {
793   let point = match endpoint_type {
794     EndpointType::Community => "c",
795     EndpointType::Person => "u",
796     EndpointType::Post => "post",
797     EndpointType::Comment => "comment",
798     EndpointType::PrivateMessage => "private_message",
799   };
800
801   Ok(Url::parse(&format!("{domain}/{point}/{name}"))?.into())
802 }
803
804 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
805   Ok(Url::parse(&format!("{actor_id}/followers"))?.into())
806 }
807
808 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
809   Ok(Url::parse(&format!("{actor_id}/inbox"))?.into())
810 }
811
812 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
813   let mut actor_id: Url = actor_id.clone().into();
814   actor_id.set_path("site_inbox");
815   Ok(actor_id.into())
816 }
817
818 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
819   let actor_id: Url = actor_id.clone().into();
820   let url = format!(
821     "{}://{}{}/inbox",
822     &actor_id.scheme(),
823     &actor_id.host_str().context(location_info!())?,
824     if let Some(port) = actor_id.port() {
825       format!(":{port}")
826     } else {
827       String::new()
828     },
829   );
830   Ok(Url::parse(&url)?.into())
831 }
832
833 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
834   Ok(Url::parse(&format!("{actor_id}/outbox"))?.into())
835 }
836
837 pub fn generate_featured_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
838   Ok(Url::parse(&format!("{actor_id}/featured"))?.into())
839 }
840
841 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
842   Ok(Url::parse(&format!("{community_id}/moderators"))?.into())
843 }