1 use crate::{request::purge_image_from_pictrs, sensitive::Sensitive, site::FederatedInstances};
3 use chrono::NaiveDateTime;
5 impls::person::is_banned,
6 newtypes::{CommunityId, DbUrl, LocalUserId, PersonId, PostId},
8 comment::{Comment, CommentUpdateForm},
9 community::{Community, CommunityUpdateForm},
10 email_verification::{EmailVerification, EmailVerificationForm},
12 local_site::{LocalSite, RegistrationMode},
13 local_site_rate_limit::LocalSiteRateLimit,
14 password_reset_request::PasswordResetRequest,
15 person::{Person, PersonUpdateForm},
16 person_block::PersonBlock,
17 post::{Post, PostRead, PostReadForm},
18 registration_application::RegistrationApplication,
21 traits::{Crud, Readable},
26 comment_view::CommentQuery,
27 structs::{LocalUserSettingsView, LocalUserView},
29 use lemmy_db_views_actor::structs::{
30 CommunityModeratorView,
31 CommunityPersonBanView,
36 email::{send_email, translations::Lang},
39 rate_limit::RateLimitConfig,
40 settings::structs::Settings,
41 utils::{build_slur_regex, generate_random_string},
44 use reqwest_middleware::ClientWithMiddleware;
45 use rosetta_i18n::{Language, LanguageId};
46 use std::str::FromStr;
48 use url::{ParseError, Url};
50 #[tracing::instrument(skip_all)]
51 pub async fn is_mod_or_admin(
54 community_id: CommunityId,
55 ) -> Result<(), LemmyError> {
56 let is_mod_or_admin = CommunityView::is_mod_or_admin(pool, person_id, community_id).await?;
58 return Err(LemmyError::from_message("not_a_mod_or_admin"));
63 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
64 if !local_user_view.person.admin {
65 return Err(LemmyError::from_message("not_an_admin"));
70 #[tracing::instrument(skip_all)]
71 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
72 Post::read(pool, post_id)
74 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))
77 #[tracing::instrument(skip_all)]
78 pub async fn mark_post_as_read(
82 ) -> Result<PostRead, LemmyError> {
83 let post_read_form = PostReadForm { post_id, person_id };
85 PostRead::mark_as_read(pool, &post_read_form)
87 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
90 #[tracing::instrument(skip_all)]
91 pub async fn mark_post_as_unread(
95 ) -> Result<usize, LemmyError> {
96 let post_read_form = PostReadForm { post_id, person_id };
98 PostRead::mark_as_unread(pool, &post_read_form)
100 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
103 #[tracing::instrument(skip_all)]
104 pub async fn get_local_user_view_from_jwt(
108 ) -> Result<LocalUserView, LemmyError> {
109 let claims = Claims::decode(jwt, &secret.jwt_secret)
110 .map_err(|e| e.with_message("not_logged_in"))?
112 let local_user_id = LocalUserId(claims.sub);
113 let local_user_view = LocalUserView::read(pool, local_user_id).await?;
115 local_user_view.person.banned,
116 local_user_view.person.ban_expires,
117 local_user_view.person.deleted,
120 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
125 /// Checks if user's token was issued before user's password reset.
126 pub fn check_validator_time(
127 validator_time: &NaiveDateTime,
129 ) -> Result<(), LemmyError> {
130 let user_validation_time = validator_time.timestamp();
131 if user_validation_time > claims.iat {
132 Err(LemmyError::from_message("not_logged_in"))
138 #[tracing::instrument(skip_all)]
139 pub async fn get_local_user_view_from_jwt_opt(
140 jwt: Option<&Sensitive<String>>,
143 ) -> Result<Option<LocalUserView>, LemmyError> {
145 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
150 #[tracing::instrument(skip_all)]
151 pub async fn get_local_user_settings_view_from_jwt_opt(
152 jwt: Option<&Sensitive<String>>,
155 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
158 let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
159 .map_err(|e| e.with_message("not_logged_in"))?
161 let local_user_id = LocalUserId(claims.sub);
162 let local_user_view = LocalUserSettingsView::read(pool, local_user_id).await?;
164 local_user_view.person.banned,
165 local_user_view.person.ban_expires,
166 local_user_view.person.deleted,
169 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
171 Ok(Some(local_user_view))
176 pub fn check_user_valid(
178 ban_expires: Option<NaiveDateTime>,
180 ) -> Result<(), LemmyError> {
181 // Check for a site ban
182 if is_banned(banned, ban_expires) {
183 return Err(LemmyError::from_message("site_ban"));
186 // check for account deletion
188 return Err(LemmyError::from_message("deleted"));
194 #[tracing::instrument(skip_all)]
195 pub async fn check_community_ban(
197 community_id: CommunityId,
199 ) -> Result<(), LemmyError> {
200 let is_banned = CommunityPersonBanView::get(pool, person_id, community_id)
204 Err(LemmyError::from_message("community_ban"))
210 #[tracing::instrument(skip_all)]
211 pub async fn check_community_deleted_or_removed(
212 community_id: CommunityId,
214 ) -> Result<(), LemmyError> {
215 let community = Community::read(pool, community_id)
217 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
218 if community.deleted || community.removed {
219 Err(LemmyError::from_message("deleted"))
225 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
226 if post.deleted || post.removed {
227 Err(LemmyError::from_message("deleted"))
233 #[tracing::instrument(skip_all)]
234 pub async fn check_person_block(
236 potential_blocker_id: PersonId,
238 ) -> Result<(), LemmyError> {
239 let is_blocked = PersonBlock::read(pool, potential_blocker_id, my_id)
243 Err(LemmyError::from_message("person_block"))
249 #[tracing::instrument(skip_all)]
250 pub fn check_downvotes_enabled(score: i16, local_site: &LocalSite) -> Result<(), LemmyError> {
251 if score == -1 && !local_site.enable_downvotes {
252 return Err(LemmyError::from_message("downvotes_disabled"));
257 #[tracing::instrument(skip_all)]
258 pub fn check_private_instance(
259 local_user_view: &Option<LocalUserView>,
260 local_site: &LocalSite,
261 ) -> Result<(), LemmyError> {
262 if local_user_view.is_none() && local_site.private_instance {
263 return Err(LemmyError::from_message("instance_is_private"));
268 #[tracing::instrument(skip_all)]
269 pub async fn build_federated_instances(
270 local_site: &LocalSite,
272 ) -> Result<Option<FederatedInstances>, LemmyError> {
273 if local_site.federation_enabled {
274 // TODO I hate that this requires 3 queries
275 let linked = Instance::linked(pool).await?;
276 let allowed = Instance::allowlist(pool).await?;
277 let blocked = Instance::blocklist(pool).await?;
279 // These can return empty vectors, so convert them to options
280 let allowed = (!allowed.is_empty()).then_some(allowed);
281 let blocked = (!blocked.is_empty()).then_some(blocked);
283 Ok(Some(FederatedInstances {
293 /// Checks the password length
294 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
295 if !(10..=60).contains(&pass.chars().count()) {
296 Err(LemmyError::from_message("invalid_password"))
302 /// Checks the site description length
303 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
304 if description.len() > 150 {
305 Err(LemmyError::from_message("site_description_length_overflow"))
311 /// Checks for a honeypot. If this field is filled, fail the rest of the function
312 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
313 if honeypot.is_some() && honeypot != &Some(String::new()) {
314 Err(LemmyError::from_message("honeypot_fail"))
320 pub fn send_email_to_user(
321 local_user_view: &LocalUserView,
326 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
330 if let Some(user_email) = &local_user_view.local_user.email {
334 &local_user_view.person.name,
339 Err(e) => warn!("{}", e),
344 pub async fn send_password_reset_email(
345 user: &LocalUserView,
348 ) -> Result<(), LemmyError> {
349 // Generate a random token
350 let token = generate_random_string();
353 let token2 = token.clone();
354 let local_user_id = user.local_user.id;
355 PasswordResetRequest::create_token(pool, local_user_id, &token2).await?;
357 let email = &user.local_user.email.clone().expect("email");
358 let lang = get_interface_language(user);
359 let subject = &lang.password_reset_subject(&user.person.name);
360 let protocol_and_hostname = settings.get_protocol_and_hostname();
361 let reset_link = format!("{}/password_change/{}", protocol_and_hostname, &token);
362 let body = &lang.password_reset_body(reset_link, &user.person.name);
363 send_email(subject, email, &user.person.name, body, settings)
366 /// Send a verification email
367 pub async fn send_verification_email(
368 user: &LocalUserView,
372 ) -> Result<(), LemmyError> {
373 let form = EmailVerificationForm {
374 local_user_id: user.local_user.id,
375 email: new_email.to_string(),
376 verification_token: generate_random_string(),
378 let verify_link = format!(
379 "{}/verify_email/{}",
380 settings.get_protocol_and_hostname(),
381 &form.verification_token
383 EmailVerification::create(pool, &form).await?;
385 let lang = get_interface_language(user);
386 let subject = lang.verify_email_subject(&settings.hostname);
387 let body = lang.verify_email_body(&settings.hostname, &user.person.name, verify_link);
388 send_email(&subject, new_email, &user.person.name, &body, settings)?;
393 pub fn send_email_verification_success(
394 user: &LocalUserView,
396 ) -> Result<(), LemmyError> {
397 let email = &user.local_user.email.clone().expect("email");
398 let lang = get_interface_language(user);
399 let subject = &lang.email_verified_subject(&user.person.actor_id);
400 let body = &lang.email_verified_body();
401 send_email(subject, email, &user.person.name, body, settings)
404 pub fn get_interface_language(user: &LocalUserView) -> Lang {
405 lang_str_to_lang(&user.local_user.interface_language)
408 pub fn get_interface_language_from_settings(user: &LocalUserSettingsView) -> Lang {
409 lang_str_to_lang(&user.local_user.interface_language)
412 fn lang_str_to_lang(lang: &str) -> Lang {
413 let lang_id = LanguageId::new(lang);
414 Lang::from_language_id(&lang_id).unwrap_or_else(|| {
415 let en = LanguageId::new("en");
416 Lang::from_language_id(&en).expect("default language")
420 pub fn local_site_rate_limit_to_rate_limit_config(
421 local_site_rate_limit: &LocalSiteRateLimit,
422 ) -> RateLimitConfig {
423 let l = local_site_rate_limit;
426 message_per_second: l.message_per_second,
428 post_per_second: l.post_per_second,
429 register: l.register,
430 register_per_second: l.register_per_second,
432 image_per_second: l.image_per_second,
434 comment_per_second: l.comment_per_second,
436 search_per_second: l.search_per_second,
440 pub fn local_site_to_slur_regex(local_site: &LocalSite) -> Option<Regex> {
441 build_slur_regex(local_site.slur_filter_regex.as_deref())
444 pub fn local_site_opt_to_slur_regex(local_site: &Option<LocalSite>) -> Option<Regex> {
447 .map(local_site_to_slur_regex)
451 pub fn send_application_approved_email(
452 user: &LocalUserView,
454 ) -> Result<(), LemmyError> {
455 let email = &user.local_user.email.clone().expect("email");
456 let lang = get_interface_language(user);
457 let subject = lang.registration_approved_subject(&user.person.actor_id);
458 let body = lang.registration_approved_body(&settings.hostname);
459 send_email(&subject, email, &user.person.name, &body, settings)
462 /// Send a new applicant email notification to all admins
463 pub async fn send_new_applicant_email_to_admins(
464 applicant_username: &str,
467 ) -> Result<(), LemmyError> {
468 // Collect the admins with emails
469 let admins = LocalUserSettingsView::list_admins_with_emails(pool).await?;
471 let applications_link = &format!(
472 "{}/registration_applications",
473 settings.get_protocol_and_hostname(),
476 for admin in &admins {
477 let email = &admin.local_user.email.clone().expect("email");
478 let lang = get_interface_language_from_settings(admin);
479 let subject = lang.new_application_subject(&settings.hostname, applicant_username);
480 let body = lang.new_application_body(applications_link);
481 send_email(&subject, email, &admin.person.name, &body, settings)?;
486 pub async fn check_registration_application(
487 local_user_view: &LocalUserView,
488 local_site: &LocalSite,
490 ) -> Result<(), LemmyError> {
491 if local_site.registration_mode == RegistrationMode::RequireApplication
492 && !local_user_view.local_user.accepted_application
493 && !local_user_view.person.admin
495 // Fetch the registration, see if its denied
496 let local_user_id = local_user_view.local_user.id;
497 let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?;
498 if let Some(deny_reason) = registration.deny_reason {
499 let lang = get_interface_language(local_user_view);
500 let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason);
501 return Err(LemmyError::from_message(®istration_denied_message));
503 return Err(LemmyError::from_message("registration_application_pending"));
509 pub fn check_private_instance_and_federation_enabled(
510 local_site: &LocalSite,
511 ) -> Result<(), LemmyError> {
512 if local_site.private_instance && local_site.federation_enabled {
513 return Err(LemmyError::from_message(
514 "Cannot have both private instance and federation enabled.",
520 pub async fn purge_image_posts_for_person(
521 banned_person_id: PersonId,
524 client: &ClientWithMiddleware,
525 ) -> Result<(), LemmyError> {
526 let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
528 if let Some(url) = post.url {
529 purge_image_from_pictrs(client, settings, &url).await.ok();
531 if let Some(thumbnail_url) = post.thumbnail_url {
532 purge_image_from_pictrs(client, settings, &thumbnail_url)
538 Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
543 pub async fn purge_image_posts_for_community(
544 banned_community_id: CommunityId,
547 client: &ClientWithMiddleware,
548 ) -> Result<(), LemmyError> {
549 let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?;
551 if let Some(url) = post.url {
552 purge_image_from_pictrs(client, settings, &url).await.ok();
554 if let Some(thumbnail_url) = post.thumbnail_url {
555 purge_image_from_pictrs(client, settings, &thumbnail_url)
561 Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?;
566 pub async fn remove_user_data(
567 banned_person_id: PersonId,
570 client: &ClientWithMiddleware,
571 ) -> Result<(), LemmyError> {
573 let person = Person::read(pool, banned_person_id).await?;
574 if let Some(avatar) = person.avatar {
575 purge_image_from_pictrs(client, settings, &avatar)
579 if let Some(banner) = person.banner {
580 purge_image_from_pictrs(client, settings, &banner)
585 // Update the fields to None
589 &PersonUpdateForm::builder()
597 Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
600 purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
603 // Remove all communities where they're the top mod
604 // for now, remove the communities manually
605 let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
607 // Filter to only this banned users top communities
608 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
610 .filter(|fmc| fmc.moderator.id == banned_person_id)
613 for first_mod_community in banned_user_first_communities {
614 let community_id = first_mod_community.community.id;
618 &CommunityUpdateForm::builder().removed(Some(true)).build(),
622 // Delete the community images
623 if let Some(icon) = first_mod_community.community.icon {
624 purge_image_from_pictrs(client, settings, &icon).await.ok();
626 if let Some(banner) = first_mod_community.community.banner {
627 purge_image_from_pictrs(client, settings, &banner)
631 // Update the fields to None
635 &CommunityUpdateForm::builder()
644 Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
649 pub async fn remove_user_data_in_community(
650 community_id: CommunityId,
651 banned_person_id: PersonId,
653 ) -> Result<(), LemmyError> {
655 Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
658 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
659 let comments = CommentQuery::builder()
661 .creator_id(Some(banned_person_id))
662 .community_id(Some(community_id))
663 .limit(Some(i64::MAX))
668 for comment_view in &comments {
669 let comment_id = comment_view.comment.id;
673 &CommentUpdateForm::builder().removed(Some(true)).build(),
681 pub async fn delete_user_account(
685 client: &ClientWithMiddleware,
686 ) -> Result<(), LemmyError> {
687 // Delete their images
688 let person = Person::read(pool, person_id).await?;
689 if let Some(avatar) = person.avatar {
690 purge_image_from_pictrs(client, settings, &avatar)
694 if let Some(banner) = person.banner {
695 purge_image_from_pictrs(client, settings, &banner)
699 // No need to update avatar and banner, those are handled in Person::delete_account
702 Comment::permadelete_for_creator(pool, person_id)
704 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
707 Post::permadelete_for_creator(pool, person_id)
709 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
712 purge_image_posts_for_person(person_id, pool, settings, client).await?;
714 Person::delete_account(pool, person_id).await?;
719 pub fn listing_type_with_site_default(
720 listing_type: Option<ListingType>,
721 local_site: &LocalSite,
722 ) -> Result<ListingType, LemmyError> {
723 Ok(listing_type.unwrap_or(ListingType::from_str(
724 &local_site.default_post_listing_type,
730 use crate::utils::{honeypot_check, password_length_check};
734 fn password_length() {
735 assert!(password_length_check("Õ¼¾°3yË,o¸ãtÌÈú|ÇÁÙAøüÒI©·¤(T]/ð>æºWæ[C¤bªWöaÃÎñ·{=û³&§½K/c").is_ok());
736 assert!(password_length_check("1234567890").is_ok());
737 assert!(password_length_check("short").is_err());
738 assert!(password_length_check("looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong").is_err());
743 assert!(honeypot_check(&None).is_ok());
744 assert!(honeypot_check(&Some(String::new())).is_ok());
745 assert!(honeypot_check(&Some("1".to_string())).is_err());
746 assert!(honeypot_check(&Some("message".to_string())).is_err());
750 pub enum EndpointType {
758 /// Generates an apub endpoint for a given domain, IE xyz.tld
759 pub fn generate_local_apub_endpoint(
760 endpoint_type: EndpointType,
763 ) -> Result<DbUrl, ParseError> {
764 let point = match endpoint_type {
765 EndpointType::Community => "c",
766 EndpointType::Person => "u",
767 EndpointType::Post => "post",
768 EndpointType::Comment => "comment",
769 EndpointType::PrivateMessage => "private_message",
772 Ok(Url::parse(&format!("{domain}/{point}/{name}"))?.into())
775 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
776 Ok(Url::parse(&format!("{actor_id}/followers"))?.into())
779 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
780 Ok(Url::parse(&format!("{actor_id}/inbox"))?.into())
783 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
784 let mut actor_id: Url = actor_id.clone().into();
785 actor_id.set_path("site_inbox");
789 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
790 let actor_id: Url = actor_id.clone().into();
794 &actor_id.host_str().context(location_info!())?,
795 if let Some(port) = actor_id.port() {
801 Ok(Url::parse(&url)?.into())
804 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
805 Ok(Url::parse(&format!("{actor_id}/outbox"))?.into())
808 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
809 Ok(Url::parse(&format!("{community_id}/moderators"))?.into())