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},
25 use lemmy_db_views::{comment_view::CommentQuery, structs::LocalUserView};
26 use lemmy_db_views_actor::structs::{
27 CommunityModeratorView,
28 CommunityPersonBanView,
34 email::{send_email, translations::Lang},
37 rate_limit::RateLimitConfig,
38 settings::structs::Settings,
39 utils::slurs::build_slur_regex,
42 use reqwest_middleware::ClientWithMiddleware;
43 use rosetta_i18n::{Language, LanguageId};
44 use std::str::FromStr;
46 use url::{ParseError, Url};
48 #[tracing::instrument(skip_all)]
49 pub async fn is_mod_or_admin(
52 community_id: CommunityId,
53 ) -> Result<(), LemmyError> {
54 let is_mod_or_admin = CommunityView::is_mod_or_admin(pool, person_id, community_id).await?;
56 return Err(LemmyError::from_message("not_a_mod_or_admin"));
61 #[tracing::instrument(skip_all)]
62 pub async fn is_mod_or_admin_opt(
64 local_user_view: Option<&LocalUserView>,
65 community_id: Option<CommunityId>,
66 ) -> Result<(), LemmyError> {
67 if let Some(local_user_view) = local_user_view {
68 if let Some(community_id) = community_id {
69 is_mod_or_admin(pool, local_user_view.person.id, community_id).await
71 is_admin(local_user_view)
74 Err(LemmyError::from_message("not_a_mod_or_admin"))
78 pub async fn is_top_admin(pool: &DbPool, person_id: PersonId) -> Result<(), LemmyError> {
79 let admins = PersonView::admins(pool).await?;
80 let top_admin = admins
82 .ok_or_else(|| LemmyError::from_message("no admins"))?;
84 if top_admin.person.id != person_id {
85 return Err(LemmyError::from_message("not_top_admin"));
90 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
91 if !local_user_view.person.admin {
92 return Err(LemmyError::from_message("not_an_admin"));
98 local_user_view: &LocalUserView,
99 community_mods: &[CommunityModeratorView],
100 ) -> Result<(), LemmyError> {
101 if local_user_view.person.id
104 .map(|cm| cm.moderator.id)
105 .unwrap_or(PersonId(0))
107 return Err(LemmyError::from_message("not_top_mod"));
112 #[tracing::instrument(skip_all)]
113 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
114 Post::read(pool, post_id)
116 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))
119 #[tracing::instrument(skip_all)]
120 pub async fn mark_post_as_read(
124 ) -> Result<PostRead, LemmyError> {
125 let post_read_form = PostReadForm { post_id, person_id };
127 PostRead::mark_as_read(pool, &post_read_form)
129 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
132 #[tracing::instrument(skip_all)]
133 pub async fn mark_post_as_unread(
137 ) -> Result<usize, LemmyError> {
138 let post_read_form = PostReadForm { post_id, person_id };
140 PostRead::mark_as_unread(pool, &post_read_form)
142 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
145 #[tracing::instrument(skip_all)]
146 pub async fn get_local_user_view_from_jwt(
150 ) -> Result<LocalUserView, LemmyError> {
151 let claims = Claims::decode(jwt, &secret.jwt_secret)
152 .map_err(|e| e.with_message("not_logged_in"))?
154 let local_user_id = LocalUserId(claims.sub);
155 let local_user_view = LocalUserView::read(pool, local_user_id).await?;
157 local_user_view.person.banned,
158 local_user_view.person.ban_expires,
159 local_user_view.person.deleted,
162 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
167 /// Checks if user's token was issued before user's password reset.
168 pub fn check_validator_time(
169 validator_time: &NaiveDateTime,
171 ) -> Result<(), LemmyError> {
172 let user_validation_time = validator_time.timestamp();
173 if user_validation_time > claims.iat {
174 Err(LemmyError::from_message("not_logged_in"))
180 #[tracing::instrument(skip_all)]
181 pub async fn get_local_user_view_from_jwt_opt(
182 jwt: Option<&Sensitive<String>>,
185 ) -> Result<Option<LocalUserView>, LemmyError> {
187 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
192 #[tracing::instrument(skip_all)]
193 pub async fn get_local_user_settings_view_from_jwt_opt(
194 jwt: Option<&Sensitive<String>>,
197 ) -> Result<Option<LocalUserView>, LemmyError> {
200 let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
201 .map_err(|e| e.with_message("not_logged_in"))?
203 let local_user_id = LocalUserId(claims.sub);
204 let local_user_view = LocalUserView::read(pool, local_user_id).await?;
206 local_user_view.person.banned,
207 local_user_view.person.ban_expires,
208 local_user_view.person.deleted,
211 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
213 Ok(Some(local_user_view))
218 pub fn check_user_valid(
220 ban_expires: Option<NaiveDateTime>,
222 ) -> Result<(), LemmyError> {
223 // Check for a site ban
224 if is_banned(banned, ban_expires) {
225 return Err(LemmyError::from_message("site_ban"));
228 // check for account deletion
230 return Err(LemmyError::from_message("deleted"));
236 #[tracing::instrument(skip_all)]
237 pub async fn check_community_ban(
239 community_id: CommunityId,
241 ) -> Result<(), LemmyError> {
242 let is_banned = CommunityPersonBanView::get(pool, person_id, community_id)
246 Err(LemmyError::from_message("community_ban"))
252 #[tracing::instrument(skip_all)]
253 pub async fn check_community_deleted_or_removed(
254 community_id: CommunityId,
256 ) -> Result<(), LemmyError> {
257 let community = Community::read(pool, community_id)
259 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
260 if community.deleted || community.removed {
261 Err(LemmyError::from_message("deleted"))
267 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
268 if post.deleted || post.removed {
269 Err(LemmyError::from_message("deleted"))
275 #[tracing::instrument(skip_all)]
276 pub async fn check_person_block(
278 potential_blocker_id: PersonId,
280 ) -> Result<(), LemmyError> {
281 let is_blocked = PersonBlock::read(pool, potential_blocker_id, my_id)
285 Err(LemmyError::from_message("person_block"))
291 #[tracing::instrument(skip_all)]
292 pub fn check_downvotes_enabled(score: i16, local_site: &LocalSite) -> Result<(), LemmyError> {
293 if score == -1 && !local_site.enable_downvotes {
294 return Err(LemmyError::from_message("downvotes_disabled"));
299 #[tracing::instrument(skip_all)]
300 pub fn check_private_instance(
301 local_user_view: &Option<LocalUserView>,
302 local_site: &LocalSite,
303 ) -> Result<(), LemmyError> {
304 if local_user_view.is_none() && local_site.private_instance {
305 return Err(LemmyError::from_message("instance_is_private"));
310 #[tracing::instrument(skip_all)]
311 pub async fn build_federated_instances(
312 local_site: &LocalSite,
314 ) -> Result<Option<FederatedInstances>, LemmyError> {
315 if local_site.federation_enabled {
316 // TODO I hate that this requires 3 queries
317 let linked = Instance::linked(pool).await?;
318 let allowed = Instance::allowlist(pool).await?;
319 let blocked = Instance::blocklist(pool).await?;
321 // These can return empty vectors, so convert them to options
322 let allowed = (!allowed.is_empty()).then_some(allowed);
323 let blocked = (!blocked.is_empty()).then_some(blocked);
325 Ok(Some(FederatedInstances {
335 /// Checks the password length
336 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
337 if !(10..=60).contains(&pass.chars().count()) {
338 Err(LemmyError::from_message("invalid_password"))
344 /// Checks the site description length
345 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
346 if description.len() > 150 {
347 Err(LemmyError::from_message("site_description_length_overflow"))
353 /// Checks for a honeypot. If this field is filled, fail the rest of the function
354 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
355 if honeypot.is_some() && honeypot != &Some(String::new()) {
356 Err(LemmyError::from_message("honeypot_fail"))
362 pub fn send_email_to_user(
363 local_user_view: &LocalUserView,
368 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
372 if let Some(user_email) = &local_user_view.local_user.email {
376 &local_user_view.person.name,
381 Err(e) => warn!("{}", e),
386 pub async fn send_password_reset_email(
387 user: &LocalUserView,
390 ) -> Result<(), LemmyError> {
391 // Generate a random token
392 let token = uuid::Uuid::new_v4().to_string();
395 let token2 = token.clone();
396 let local_user_id = user.local_user.id;
397 PasswordResetRequest::create_token(pool, local_user_id, &token2).await?;
399 let email = &user.local_user.email.clone().expect("email");
400 let lang = get_interface_language(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)
408 /// Send a verification email
409 pub async fn send_verification_email(
410 user: &LocalUserView,
414 ) -> Result<(), LemmyError> {
415 let form = EmailVerificationForm {
416 local_user_id: user.local_user.id,
417 email: new_email.to_string(),
418 verification_token: uuid::Uuid::new_v4().to_string(),
420 let verify_link = format!(
421 "{}/verify_email/{}",
422 settings.get_protocol_and_hostname(),
423 &form.verification_token
425 EmailVerification::create(pool, &form).await?;
427 let lang = get_interface_language(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)?;
435 pub fn send_email_verification_success(
436 user: &LocalUserView,
438 ) -> Result<(), LemmyError> {
439 let email = &user.local_user.email.clone().expect("email");
440 let lang = get_interface_language(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)
446 pub fn get_interface_language(user: &LocalUserView) -> Lang {
447 lang_str_to_lang(&user.local_user.interface_language)
450 pub fn get_interface_language_from_settings(user: &LocalUserView) -> Lang {
451 lang_str_to_lang(&user.local_user.interface_language)
454 fn lang_str_to_lang(lang: &str) -> Lang {
455 let lang_id = LanguageId::new(lang);
456 Lang::from_language_id(&lang_id).unwrap_or_else(|| {
457 let en = LanguageId::new("en");
458 Lang::from_language_id(&en).expect("default language")
462 pub fn local_site_rate_limit_to_rate_limit_config(
463 local_site_rate_limit: &LocalSiteRateLimit,
464 ) -> RateLimitConfig {
465 let l = local_site_rate_limit;
468 message_per_second: l.message_per_second,
470 post_per_second: l.post_per_second,
471 register: l.register,
472 register_per_second: l.register_per_second,
474 image_per_second: l.image_per_second,
476 comment_per_second: l.comment_per_second,
478 search_per_second: l.search_per_second,
482 pub fn local_site_to_slur_regex(local_site: &LocalSite) -> Option<Regex> {
483 build_slur_regex(local_site.slur_filter_regex.as_deref())
486 pub fn local_site_opt_to_slur_regex(local_site: &Option<LocalSite>) -> Option<Regex> {
489 .map(local_site_to_slur_regex)
493 pub fn send_application_approved_email(
494 user: &LocalUserView,
496 ) -> Result<(), LemmyError> {
497 let email = &user.local_user.email.clone().expect("email");
498 let lang = get_interface_language(user);
499 let subject = lang.registration_approved_subject(&user.person.actor_id);
500 let body = lang.registration_approved_body(&settings.hostname);
501 send_email(&subject, email, &user.person.name, &body, settings)
504 /// Send a new applicant email notification to all admins
505 pub async fn send_new_applicant_email_to_admins(
506 applicant_username: &str,
509 ) -> Result<(), LemmyError> {
510 // Collect the admins with emails
511 let admins = LocalUserView::list_admins_with_emails(pool).await?;
513 let applications_link = &format!(
514 "{}/registration_applications",
515 settings.get_protocol_and_hostname(),
518 for admin in &admins {
519 let email = &admin.local_user.email.clone().expect("email");
520 let lang = get_interface_language_from_settings(admin);
521 let subject = lang.new_application_subject(&settings.hostname, applicant_username);
522 let body = lang.new_application_body(applications_link);
523 send_email(&subject, email, &admin.person.name, &body, settings)?;
528 /// Send a report to all admins
529 pub async fn send_new_report_email_to_admins(
530 reporter_username: &str,
531 reported_username: &str,
534 ) -> Result<(), LemmyError> {
535 // Collect the admins with emails
536 let admins = LocalUserView::list_admins_with_emails(pool).await?;
538 let reports_link = &format!("{}/reports", settings.get_protocol_and_hostname(),);
540 for admin in &admins {
541 let email = &admin.local_user.email.clone().expect("email");
542 let lang = get_interface_language_from_settings(admin);
543 let subject = lang.new_report_subject(&settings.hostname, reporter_username, reported_username);
544 let body = lang.new_report_body(reports_link);
545 send_email(&subject, email, &admin.person.name, &body, settings)?;
550 pub async fn check_registration_application(
551 local_user_view: &LocalUserView,
552 local_site: &LocalSite,
554 ) -> Result<(), LemmyError> {
555 if local_site.registration_mode == RegistrationMode::RequireApplication
556 && !local_user_view.local_user.accepted_application
557 && !local_user_view.person.admin
559 // Fetch the registration, see if its denied
560 let local_user_id = local_user_view.local_user.id;
561 let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?;
562 if let Some(deny_reason) = registration.deny_reason {
563 let lang = get_interface_language(local_user_view);
564 let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason);
565 return Err(LemmyError::from_message(®istration_denied_message));
567 return Err(LemmyError::from_message("registration_application_pending"));
573 pub fn check_private_instance_and_federation_enabled(
574 local_site: &LocalSite,
575 ) -> Result<(), LemmyError> {
576 if local_site.private_instance && local_site.federation_enabled {
577 return Err(LemmyError::from_message(
578 "Cannot have both private instance and federation enabled.",
584 pub async fn purge_image_posts_for_person(
585 banned_person_id: PersonId,
588 client: &ClientWithMiddleware,
589 ) -> Result<(), LemmyError> {
590 let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
592 if let Some(url) = post.url {
593 purge_image_from_pictrs(client, settings, &url).await.ok();
595 if let Some(thumbnail_url) = post.thumbnail_url {
596 purge_image_from_pictrs(client, settings, &thumbnail_url)
602 Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
607 pub async fn purge_image_posts_for_community(
608 banned_community_id: CommunityId,
611 client: &ClientWithMiddleware,
612 ) -> Result<(), LemmyError> {
613 let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?;
615 if let Some(url) = post.url {
616 purge_image_from_pictrs(client, settings, &url).await.ok();
618 if let Some(thumbnail_url) = post.thumbnail_url {
619 purge_image_from_pictrs(client, settings, &thumbnail_url)
625 Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?;
630 pub async fn remove_user_data(
631 banned_person_id: PersonId,
634 client: &ClientWithMiddleware,
635 ) -> Result<(), LemmyError> {
637 let person = Person::read(pool, banned_person_id).await?;
638 if let Some(avatar) = person.avatar {
639 purge_image_from_pictrs(client, settings, &avatar)
643 if let Some(banner) = person.banner {
644 purge_image_from_pictrs(client, settings, &banner)
649 // Update the fields to None
653 &PersonUpdateForm::builder()
661 Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
664 purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
667 // Remove all communities where they're the top mod
668 // for now, remove the communities manually
669 let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
671 // Filter to only this banned users top communities
672 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
674 .filter(|fmc| fmc.moderator.id == banned_person_id)
677 for first_mod_community in banned_user_first_communities {
678 let community_id = first_mod_community.community.id;
682 &CommunityUpdateForm::builder().removed(Some(true)).build(),
686 // Delete the community images
687 if let Some(icon) = first_mod_community.community.icon {
688 purge_image_from_pictrs(client, settings, &icon).await.ok();
690 if let Some(banner) = first_mod_community.community.banner {
691 purge_image_from_pictrs(client, settings, &banner)
695 // Update the fields to None
699 &CommunityUpdateForm::builder()
708 Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
713 pub async fn remove_user_data_in_community(
714 community_id: CommunityId,
715 banned_person_id: PersonId,
717 ) -> Result<(), LemmyError> {
719 Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
722 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
723 let comments = CommentQuery::builder()
725 .creator_id(Some(banned_person_id))
726 .community_id(Some(community_id))
727 .limit(Some(i64::MAX))
732 for comment_view in &comments {
733 let comment_id = comment_view.comment.id;
737 &CommentUpdateForm::builder().removed(Some(true)).build(),
745 pub async fn delete_user_account(
749 client: &ClientWithMiddleware,
750 ) -> Result<(), LemmyError> {
751 // Delete their images
752 let person = Person::read(pool, person_id).await?;
753 if let Some(avatar) = person.avatar {
754 purge_image_from_pictrs(client, settings, &avatar)
758 if let Some(banner) = person.banner {
759 purge_image_from_pictrs(client, settings, &banner)
763 // No need to update avatar and banner, those are handled in Person::delete_account
766 Comment::permadelete_for_creator(pool, person_id)
768 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
771 Post::permadelete_for_creator(pool, person_id)
773 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
776 purge_image_posts_for_person(person_id, pool, settings, client).await?;
778 Person::delete_account(pool, person_id).await?;
783 pub fn listing_type_with_site_default(
784 listing_type: Option<ListingType>,
785 local_site: &LocalSite,
786 ) -> Result<ListingType, LemmyError> {
787 Ok(listing_type.unwrap_or(ListingType::from_str(
788 &local_site.default_post_listing_type,
794 use crate::utils::{honeypot_check, password_length_check};
798 fn password_length() {
799 assert!(password_length_check("Õ¼¾°3yË,o¸ãtÌÈú|ÇÁÙAøüÒI©·¤(T]/ð>æºWæ[C¤bªWöaÃÎñ·{=û³&§½K/c").is_ok());
800 assert!(password_length_check("1234567890").is_ok());
801 assert!(password_length_check("short").is_err());
802 assert!(password_length_check("looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong").is_err());
807 assert!(honeypot_check(&None).is_ok());
808 assert!(honeypot_check(&Some(String::new())).is_ok());
809 assert!(honeypot_check(&Some("1".to_string())).is_err());
810 assert!(honeypot_check(&Some("message".to_string())).is_err());
814 pub enum EndpointType {
822 /// Generates an apub endpoint for a given domain, IE xyz.tld
823 pub fn generate_local_apub_endpoint(
824 endpoint_type: EndpointType,
827 ) -> Result<DbUrl, ParseError> {
828 let point = match endpoint_type {
829 EndpointType::Community => "c",
830 EndpointType::Person => "u",
831 EndpointType::Post => "post",
832 EndpointType::Comment => "comment",
833 EndpointType::PrivateMessage => "private_message",
836 Ok(Url::parse(&format!("{domain}/{point}/{name}"))?.into())
839 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
840 Ok(Url::parse(&format!("{actor_id}/followers"))?.into())
843 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
844 Ok(Url::parse(&format!("{actor_id}/inbox"))?.into())
847 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
848 let mut actor_id: Url = actor_id.clone().into();
849 actor_id.set_path("site_inbox");
853 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
854 let actor_id: Url = actor_id.clone().into();
858 &actor_id.host_str().context(location_info!())?,
859 if let Some(port) = actor_id.port() {
865 Ok(Url::parse(&url)?.into())
868 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
869 Ok(Url::parse(&format!("{actor_id}/outbox"))?.into())
872 pub fn generate_featured_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
873 Ok(Url::parse(&format!("{actor_id}/featured"))?.into())
876 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
877 Ok(Url::parse(&format!("{community_id}/moderators"))?.into())