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,
37 email::{send_email, translations::Lang},
40 rate_limit::RateLimitConfig,
41 settings::structs::Settings,
42 utils::slurs::build_slur_regex,
45 use reqwest_middleware::ClientWithMiddleware;
46 use rosetta_i18n::{Language, LanguageId};
47 use std::str::FromStr;
49 use url::{ParseError, Url};
51 #[tracing::instrument(skip_all)]
52 pub async fn is_mod_or_admin(
55 community_id: CommunityId,
56 ) -> Result<(), LemmyError> {
57 let is_mod_or_admin = CommunityView::is_mod_or_admin(pool, person_id, community_id).await?;
59 return Err(LemmyError::from_message("not_a_mod_or_admin"));
64 #[tracing::instrument(skip_all)]
65 pub async fn is_mod_or_admin_opt(
67 local_user_view: Option<&LocalUserView>,
68 community_id: Option<CommunityId>,
69 ) -> Result<(), LemmyError> {
70 if let Some(local_user_view) = local_user_view {
71 if let Some(community_id) = community_id {
72 is_mod_or_admin(pool, local_user_view.person.id, community_id).await
74 is_admin(local_user_view)
77 Err(LemmyError::from_message("not_a_mod_or_admin"))
81 pub async fn is_top_admin(pool: &DbPool, person_id: PersonId) -> Result<(), LemmyError> {
82 let admins = PersonViewSafe::admins(pool).await?;
83 let top_admin = admins
85 .ok_or_else(|| LemmyError::from_message("no admins"))?;
87 if top_admin.person.id != person_id {
88 return Err(LemmyError::from_message("not_top_admin"));
93 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
94 if !local_user_view.person.admin {
95 return Err(LemmyError::from_message("not_an_admin"));
101 local_user_view: &LocalUserView,
102 community_mods: &[CommunityModeratorView],
103 ) -> Result<(), LemmyError> {
104 if local_user_view.person.id
107 .map(|cm| cm.moderator.id)
108 .unwrap_or(PersonId(0))
110 return Err(LemmyError::from_message("not_top_mod"));
115 #[tracing::instrument(skip_all)]
116 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
117 Post::read(pool, post_id)
119 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))
122 #[tracing::instrument(skip_all)]
123 pub async fn mark_post_as_read(
127 ) -> Result<PostRead, LemmyError> {
128 let post_read_form = PostReadForm { post_id, person_id };
130 PostRead::mark_as_read(pool, &post_read_form)
132 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
135 #[tracing::instrument(skip_all)]
136 pub async fn mark_post_as_unread(
140 ) -> Result<usize, LemmyError> {
141 let post_read_form = PostReadForm { post_id, person_id };
143 PostRead::mark_as_unread(pool, &post_read_form)
145 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
148 #[tracing::instrument(skip_all)]
149 pub async fn get_local_user_view_from_jwt(
153 ) -> Result<LocalUserView, LemmyError> {
154 let claims = Claims::decode(jwt, &secret.jwt_secret)
155 .map_err(|e| e.with_message("not_logged_in"))?
157 let local_user_id = LocalUserId(claims.sub);
158 let local_user_view = LocalUserView::read(pool, local_user_id).await?;
160 local_user_view.person.banned,
161 local_user_view.person.ban_expires,
162 local_user_view.person.deleted,
165 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
170 /// Checks if user's token was issued before user's password reset.
171 pub fn check_validator_time(
172 validator_time: &NaiveDateTime,
174 ) -> Result<(), LemmyError> {
175 let user_validation_time = validator_time.timestamp();
176 if user_validation_time > claims.iat {
177 Err(LemmyError::from_message("not_logged_in"))
183 #[tracing::instrument(skip_all)]
184 pub async fn get_local_user_view_from_jwt_opt(
185 jwt: Option<&Sensitive<String>>,
188 ) -> Result<Option<LocalUserView>, LemmyError> {
190 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
195 #[tracing::instrument(skip_all)]
196 pub async fn get_local_user_settings_view_from_jwt_opt(
197 jwt: Option<&Sensitive<String>>,
200 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
203 let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
204 .map_err(|e| e.with_message("not_logged_in"))?
206 let local_user_id = LocalUserId(claims.sub);
207 let local_user_view = LocalUserSettingsView::read(pool, local_user_id).await?;
209 local_user_view.person.banned,
210 local_user_view.person.ban_expires,
211 local_user_view.person.deleted,
214 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
216 Ok(Some(local_user_view))
221 pub fn check_user_valid(
223 ban_expires: Option<NaiveDateTime>,
225 ) -> Result<(), LemmyError> {
226 // Check for a site ban
227 if is_banned(banned, ban_expires) {
228 return Err(LemmyError::from_message("site_ban"));
231 // check for account deletion
233 return Err(LemmyError::from_message("deleted"));
239 #[tracing::instrument(skip_all)]
240 pub async fn check_community_ban(
242 community_id: CommunityId,
244 ) -> Result<(), LemmyError> {
245 let is_banned = CommunityPersonBanView::get(pool, person_id, community_id)
249 Err(LemmyError::from_message("community_ban"))
255 #[tracing::instrument(skip_all)]
256 pub async fn check_community_deleted_or_removed(
257 community_id: CommunityId,
259 ) -> Result<(), LemmyError> {
260 let community = Community::read(pool, community_id)
262 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
263 if community.deleted || community.removed {
264 Err(LemmyError::from_message("deleted"))
270 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
271 if post.deleted || post.removed {
272 Err(LemmyError::from_message("deleted"))
278 #[tracing::instrument(skip_all)]
279 pub async fn check_person_block(
281 potential_blocker_id: PersonId,
283 ) -> Result<(), LemmyError> {
284 let is_blocked = PersonBlock::read(pool, potential_blocker_id, my_id)
288 Err(LemmyError::from_message("person_block"))
294 #[tracing::instrument(skip_all)]
295 pub fn check_downvotes_enabled(score: i16, local_site: &LocalSite) -> Result<(), LemmyError> {
296 if score == -1 && !local_site.enable_downvotes {
297 return Err(LemmyError::from_message("downvotes_disabled"));
302 #[tracing::instrument(skip_all)]
303 pub fn check_private_instance(
304 local_user_view: &Option<LocalUserView>,
305 local_site: &LocalSite,
306 ) -> Result<(), LemmyError> {
307 if local_user_view.is_none() && local_site.private_instance {
308 return Err(LemmyError::from_message("instance_is_private"));
313 #[tracing::instrument(skip_all)]
314 pub async fn build_federated_instances(
315 local_site: &LocalSite,
317 ) -> Result<Option<FederatedInstances>, LemmyError> {
318 if local_site.federation_enabled {
319 // TODO I hate that this requires 3 queries
320 let linked = Instance::linked(pool).await?;
321 let allowed = Instance::allowlist(pool).await?;
322 let blocked = Instance::blocklist(pool).await?;
324 // These can return empty vectors, so convert them to options
325 let allowed = (!allowed.is_empty()).then_some(allowed);
326 let blocked = (!blocked.is_empty()).then_some(blocked);
328 Ok(Some(FederatedInstances {
338 /// Checks the password length
339 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
340 if !(10..=60).contains(&pass.chars().count()) {
341 Err(LemmyError::from_message("invalid_password"))
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"))
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() && honeypot != &Some(String::new()) {
359 Err(LemmyError::from_message("honeypot_fail"))
365 pub fn send_email_to_user(
366 local_user_view: &LocalUserView,
371 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
375 if let Some(user_email) = &local_user_view.local_user.email {
379 &local_user_view.person.name,
384 Err(e) => warn!("{}", e),
389 pub async fn send_password_reset_email(
390 user: &LocalUserView,
393 ) -> Result<(), LemmyError> {
394 // Generate a random token
395 let token = uuid::Uuid::new_v4().to_string();
398 let token2 = token.clone();
399 let local_user_id = user.local_user.id;
400 PasswordResetRequest::create_token(pool, local_user_id, &token2).await?;
402 let email = &user.local_user.email.clone().expect("email");
403 let lang = get_interface_language(user);
404 let subject = &lang.password_reset_subject(&user.person.name);
405 let protocol_and_hostname = settings.get_protocol_and_hostname();
406 let reset_link = format!("{}/password_change/{}", protocol_and_hostname, &token);
407 let body = &lang.password_reset_body(reset_link, &user.person.name);
408 send_email(subject, email, &user.person.name, body, settings)
411 /// Send a verification email
412 pub async fn send_verification_email(
413 user: &LocalUserView,
417 ) -> Result<(), LemmyError> {
418 let form = EmailVerificationForm {
419 local_user_id: user.local_user.id,
420 email: new_email.to_string(),
421 verification_token: uuid::Uuid::new_v4().to_string(),
423 let verify_link = format!(
424 "{}/verify_email/{}",
425 settings.get_protocol_and_hostname(),
426 &form.verification_token
428 EmailVerification::create(pool, &form).await?;
430 let lang = get_interface_language(user);
431 let subject = lang.verify_email_subject(&settings.hostname);
432 let body = lang.verify_email_body(&settings.hostname, &user.person.name, verify_link);
433 send_email(&subject, new_email, &user.person.name, &body, settings)?;
438 pub fn send_email_verification_success(
439 user: &LocalUserView,
441 ) -> Result<(), LemmyError> {
442 let email = &user.local_user.email.clone().expect("email");
443 let lang = get_interface_language(user);
444 let subject = &lang.email_verified_subject(&user.person.actor_id);
445 let body = &lang.email_verified_body();
446 send_email(subject, email, &user.person.name, body, settings)
449 pub fn get_interface_language(user: &LocalUserView) -> Lang {
450 lang_str_to_lang(&user.local_user.interface_language)
453 pub fn get_interface_language_from_settings(user: &LocalUserSettingsView) -> Lang {
454 lang_str_to_lang(&user.local_user.interface_language)
457 fn lang_str_to_lang(lang: &str) -> Lang {
458 let lang_id = LanguageId::new(lang);
459 Lang::from_language_id(&lang_id).unwrap_or_else(|| {
460 let en = LanguageId::new("en");
461 Lang::from_language_id(&en).expect("default language")
465 pub fn local_site_rate_limit_to_rate_limit_config(
466 local_site_rate_limit: &LocalSiteRateLimit,
467 ) -> RateLimitConfig {
468 let l = local_site_rate_limit;
471 message_per_second: l.message_per_second,
473 post_per_second: l.post_per_second,
474 register: l.register,
475 register_per_second: l.register_per_second,
477 image_per_second: l.image_per_second,
479 comment_per_second: l.comment_per_second,
481 search_per_second: l.search_per_second,
485 pub fn local_site_to_slur_regex(local_site: &LocalSite) -> Option<Regex> {
486 build_slur_regex(local_site.slur_filter_regex.as_deref())
489 pub fn local_site_opt_to_slur_regex(local_site: &Option<LocalSite>) -> Option<Regex> {
492 .map(local_site_to_slur_regex)
496 pub fn send_application_approved_email(
497 user: &LocalUserView,
499 ) -> Result<(), LemmyError> {
500 let email = &user.local_user.email.clone().expect("email");
501 let lang = get_interface_language(user);
502 let subject = lang.registration_approved_subject(&user.person.actor_id);
503 let body = lang.registration_approved_body(&settings.hostname);
504 send_email(&subject, email, &user.person.name, &body, settings)
507 /// Send a new applicant email notification to all admins
508 pub async fn send_new_applicant_email_to_admins(
509 applicant_username: &str,
512 ) -> Result<(), LemmyError> {
513 // Collect the admins with emails
514 let admins = LocalUserSettingsView::list_admins_with_emails(pool).await?;
516 let applications_link = &format!(
517 "{}/registration_applications",
518 settings.get_protocol_and_hostname(),
521 for admin in &admins {
522 let email = &admin.local_user.email.clone().expect("email");
523 let lang = get_interface_language_from_settings(admin);
524 let subject = lang.new_application_subject(&settings.hostname, applicant_username);
525 let body = lang.new_application_body(applications_link);
526 send_email(&subject, email, &admin.person.name, &body, settings)?;
531 /// Send a report to all admins
532 pub async fn send_new_report_email_to_admins(
533 reporter_username: &str,
534 reported_username: &str,
537 ) -> Result<(), LemmyError> {
538 // Collect the admins with emails
539 let admins = LocalUserSettingsView::list_admins_with_emails(pool).await?;
541 let reports_link = &format!("{}/reports", settings.get_protocol_and_hostname(),);
543 for admin in &admins {
544 let email = &admin.local_user.email.clone().expect("email");
545 let lang = get_interface_language_from_settings(admin);
546 let subject = lang.new_report_subject(&settings.hostname, reporter_username, reported_username);
547 let body = lang.new_report_body(reports_link);
548 send_email(&subject, email, &admin.person.name, &body, settings)?;
553 pub async fn check_registration_application(
554 local_user_view: &LocalUserView,
555 local_site: &LocalSite,
557 ) -> Result<(), LemmyError> {
558 if local_site.registration_mode == RegistrationMode::RequireApplication
559 && !local_user_view.local_user.accepted_application
560 && !local_user_view.person.admin
562 // Fetch the registration, see if its denied
563 let local_user_id = local_user_view.local_user.id;
564 let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?;
565 if let Some(deny_reason) = registration.deny_reason {
566 let lang = get_interface_language(local_user_view);
567 let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason);
568 return Err(LemmyError::from_message(®istration_denied_message));
570 return Err(LemmyError::from_message("registration_application_pending"));
576 pub fn check_private_instance_and_federation_enabled(
577 local_site: &LocalSite,
578 ) -> Result<(), LemmyError> {
579 if local_site.private_instance && local_site.federation_enabled {
580 return Err(LemmyError::from_message(
581 "Cannot have both private instance and federation enabled.",
587 pub async fn purge_image_posts_for_person(
588 banned_person_id: PersonId,
591 client: &ClientWithMiddleware,
592 ) -> Result<(), LemmyError> {
593 let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
595 if let Some(url) = post.url {
596 purge_image_from_pictrs(client, settings, &url).await.ok();
598 if let Some(thumbnail_url) = post.thumbnail_url {
599 purge_image_from_pictrs(client, settings, &thumbnail_url)
605 Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
610 pub async fn purge_image_posts_for_community(
611 banned_community_id: CommunityId,
614 client: &ClientWithMiddleware,
615 ) -> Result<(), LemmyError> {
616 let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?;
618 if let Some(url) = post.url {
619 purge_image_from_pictrs(client, settings, &url).await.ok();
621 if let Some(thumbnail_url) = post.thumbnail_url {
622 purge_image_from_pictrs(client, settings, &thumbnail_url)
628 Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?;
633 pub async fn remove_user_data(
634 banned_person_id: PersonId,
637 client: &ClientWithMiddleware,
638 ) -> Result<(), LemmyError> {
640 let person = Person::read(pool, banned_person_id).await?;
641 if let Some(avatar) = person.avatar {
642 purge_image_from_pictrs(client, settings, &avatar)
646 if let Some(banner) = person.banner {
647 purge_image_from_pictrs(client, settings, &banner)
652 // Update the fields to None
656 &PersonUpdateForm::builder()
664 Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
667 purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
670 // Remove all communities where they're the top mod
671 // for now, remove the communities manually
672 let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
674 // Filter to only this banned users top communities
675 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
677 .filter(|fmc| fmc.moderator.id == banned_person_id)
680 for first_mod_community in banned_user_first_communities {
681 let community_id = first_mod_community.community.id;
685 &CommunityUpdateForm::builder().removed(Some(true)).build(),
689 // Delete the community images
690 if let Some(icon) = first_mod_community.community.icon {
691 purge_image_from_pictrs(client, settings, &icon).await.ok();
693 if let Some(banner) = first_mod_community.community.banner {
694 purge_image_from_pictrs(client, settings, &banner)
698 // Update the fields to None
702 &CommunityUpdateForm::builder()
711 Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
716 pub async fn remove_user_data_in_community(
717 community_id: CommunityId,
718 banned_person_id: PersonId,
720 ) -> Result<(), LemmyError> {
722 Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
725 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
726 let comments = CommentQuery::builder()
728 .creator_id(Some(banned_person_id))
729 .community_id(Some(community_id))
730 .limit(Some(i64::MAX))
735 for comment_view in &comments {
736 let comment_id = comment_view.comment.id;
740 &CommentUpdateForm::builder().removed(Some(true)).build(),
748 pub async fn delete_user_account(
752 client: &ClientWithMiddleware,
753 ) -> Result<(), LemmyError> {
754 // Delete their images
755 let person = Person::read(pool, person_id).await?;
756 if let Some(avatar) = person.avatar {
757 purge_image_from_pictrs(client, settings, &avatar)
761 if let Some(banner) = person.banner {
762 purge_image_from_pictrs(client, settings, &banner)
766 // No need to update avatar and banner, those are handled in Person::delete_account
769 Comment::permadelete_for_creator(pool, person_id)
771 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
774 Post::permadelete_for_creator(pool, person_id)
776 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
779 purge_image_posts_for_person(person_id, pool, settings, client).await?;
781 Person::delete_account(pool, person_id).await?;
786 pub fn listing_type_with_site_default(
787 listing_type: Option<ListingType>,
788 local_site: &LocalSite,
789 ) -> Result<ListingType, LemmyError> {
790 Ok(listing_type.unwrap_or(ListingType::from_str(
791 &local_site.default_post_listing_type,
797 use crate::utils::{honeypot_check, password_length_check};
801 fn password_length() {
802 assert!(password_length_check("Õ¼¾°3yË,o¸ãtÌÈú|ÇÁÙAøüÒI©·¤(T]/ð>æºWæ[C¤bªWöaÃÎñ·{=û³&§½K/c").is_ok());
803 assert!(password_length_check("1234567890").is_ok());
804 assert!(password_length_check("short").is_err());
805 assert!(password_length_check("looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong").is_err());
810 assert!(honeypot_check(&None).is_ok());
811 assert!(honeypot_check(&Some(String::new())).is_ok());
812 assert!(honeypot_check(&Some("1".to_string())).is_err());
813 assert!(honeypot_check(&Some("message".to_string())).is_err());
817 pub enum EndpointType {
825 /// Generates an apub endpoint for a given domain, IE xyz.tld
826 pub fn generate_local_apub_endpoint(
827 endpoint_type: EndpointType,
830 ) -> Result<DbUrl, ParseError> {
831 let point = match endpoint_type {
832 EndpointType::Community => "c",
833 EndpointType::Person => "u",
834 EndpointType::Post => "post",
835 EndpointType::Comment => "comment",
836 EndpointType::PrivateMessage => "private_message",
839 Ok(Url::parse(&format!("{domain}/{point}/{name}"))?.into())
842 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
843 Ok(Url::parse(&format!("{actor_id}/followers"))?.into())
846 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
847 Ok(Url::parse(&format!("{actor_id}/inbox"))?.into())
850 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
851 let mut actor_id: Url = actor_id.clone().into();
852 actor_id.set_path("site_inbox");
856 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
857 let actor_id: Url = actor_id.clone().into();
861 &actor_id.host_str().context(location_info!())?,
862 if let Some(port) = actor_id.port() {
868 Ok(Url::parse(&url)?.into())
871 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
872 Ok(Url::parse(&format!("{actor_id}/outbox"))?.into())
875 pub fn generate_featured_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
876 Ok(Url::parse(&format!("{actor_id}/featured"))?.into())
879 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
880 Ok(Url::parse(&format!("{community_id}/moderators"))?.into())