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::{build_slur_regex, generate_random_string},
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 pub async fn is_top_admin(pool: &DbPool, person_id: PersonId) -> Result<(), LemmyError> {
65 let admins = PersonViewSafe::admins(pool).await?;
66 let top_admin = admins
68 .ok_or_else(|| LemmyError::from_message("no admins"))?;
70 if top_admin.person.id != person_id {
71 return Err(LemmyError::from_message("not_top_admin"));
76 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
77 if !local_user_view.person.admin {
78 return Err(LemmyError::from_message("not_an_admin"));
83 #[tracing::instrument(skip_all)]
84 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
85 Post::read(pool, post_id)
87 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))
90 #[tracing::instrument(skip_all)]
91 pub async fn mark_post_as_read(
95 ) -> Result<PostRead, LemmyError> {
96 let post_read_form = PostReadForm { post_id, person_id };
98 PostRead::mark_as_read(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 mark_post_as_unread(
108 ) -> Result<usize, LemmyError> {
109 let post_read_form = PostReadForm { post_id, person_id };
111 PostRead::mark_as_unread(pool, &post_read_form)
113 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
116 #[tracing::instrument(skip_all)]
117 pub async fn get_local_user_view_from_jwt(
121 ) -> Result<LocalUserView, LemmyError> {
122 let claims = Claims::decode(jwt, &secret.jwt_secret)
123 .map_err(|e| e.with_message("not_logged_in"))?
125 let local_user_id = LocalUserId(claims.sub);
126 let local_user_view = LocalUserView::read(pool, local_user_id).await?;
128 local_user_view.person.banned,
129 local_user_view.person.ban_expires,
130 local_user_view.person.deleted,
133 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
138 /// Checks if user's token was issued before user's password reset.
139 pub fn check_validator_time(
140 validator_time: &NaiveDateTime,
142 ) -> Result<(), LemmyError> {
143 let user_validation_time = validator_time.timestamp();
144 if user_validation_time > claims.iat {
145 Err(LemmyError::from_message("not_logged_in"))
151 #[tracing::instrument(skip_all)]
152 pub async fn get_local_user_view_from_jwt_opt(
153 jwt: Option<&Sensitive<String>>,
156 ) -> Result<Option<LocalUserView>, LemmyError> {
158 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
163 #[tracing::instrument(skip_all)]
164 pub async fn get_local_user_settings_view_from_jwt_opt(
165 jwt: Option<&Sensitive<String>>,
168 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
171 let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
172 .map_err(|e| e.with_message("not_logged_in"))?
174 let local_user_id = LocalUserId(claims.sub);
175 let local_user_view = LocalUserSettingsView::read(pool, local_user_id).await?;
177 local_user_view.person.banned,
178 local_user_view.person.ban_expires,
179 local_user_view.person.deleted,
182 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
184 Ok(Some(local_user_view))
189 pub fn check_user_valid(
191 ban_expires: Option<NaiveDateTime>,
193 ) -> Result<(), LemmyError> {
194 // Check for a site ban
195 if is_banned(banned, ban_expires) {
196 return Err(LemmyError::from_message("site_ban"));
199 // check for account deletion
201 return Err(LemmyError::from_message("deleted"));
207 #[tracing::instrument(skip_all)]
208 pub async fn check_community_ban(
210 community_id: CommunityId,
212 ) -> Result<(), LemmyError> {
213 let is_banned = CommunityPersonBanView::get(pool, person_id, community_id)
217 Err(LemmyError::from_message("community_ban"))
223 #[tracing::instrument(skip_all)]
224 pub async fn check_community_deleted_or_removed(
225 community_id: CommunityId,
227 ) -> Result<(), LemmyError> {
228 let community = Community::read(pool, community_id)
230 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
231 if community.deleted || community.removed {
232 Err(LemmyError::from_message("deleted"))
238 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
239 if post.deleted || post.removed {
240 Err(LemmyError::from_message("deleted"))
246 #[tracing::instrument(skip_all)]
247 pub async fn check_person_block(
249 potential_blocker_id: PersonId,
251 ) -> Result<(), LemmyError> {
252 let is_blocked = PersonBlock::read(pool, potential_blocker_id, my_id)
256 Err(LemmyError::from_message("person_block"))
262 #[tracing::instrument(skip_all)]
263 pub fn check_downvotes_enabled(score: i16, local_site: &LocalSite) -> Result<(), LemmyError> {
264 if score == -1 && !local_site.enable_downvotes {
265 return Err(LemmyError::from_message("downvotes_disabled"));
270 #[tracing::instrument(skip_all)]
271 pub fn check_private_instance(
272 local_user_view: &Option<LocalUserView>,
273 local_site: &LocalSite,
274 ) -> Result<(), LemmyError> {
275 if local_user_view.is_none() && local_site.private_instance {
276 return Err(LemmyError::from_message("instance_is_private"));
281 #[tracing::instrument(skip_all)]
282 pub async fn build_federated_instances(
283 local_site: &LocalSite,
285 ) -> Result<Option<FederatedInstances>, LemmyError> {
286 if local_site.federation_enabled {
287 // TODO I hate that this requires 3 queries
288 let linked = Instance::linked(pool).await?;
289 let allowed = Instance::allowlist(pool).await?;
290 let blocked = Instance::blocklist(pool).await?;
292 // These can return empty vectors, so convert them to options
293 let allowed = (!allowed.is_empty()).then_some(allowed);
294 let blocked = (!blocked.is_empty()).then_some(blocked);
296 Ok(Some(FederatedInstances {
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"))
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"))
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"))
333 pub fn send_email_to_user(
334 local_user_view: &LocalUserView,
339 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
343 if let Some(user_email) = &local_user_view.local_user.email {
347 &local_user_view.person.name,
352 Err(e) => warn!("{}", e),
357 pub async fn send_password_reset_email(
358 user: &LocalUserView,
361 ) -> Result<(), LemmyError> {
362 // Generate a random token
363 let token = generate_random_string();
366 let token2 = token.clone();
367 let local_user_id = user.local_user.id;
368 PasswordResetRequest::create_token(pool, local_user_id, &token2).await?;
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)
379 /// Send a verification email
380 pub async fn send_verification_email(
381 user: &LocalUserView,
385 ) -> Result<(), LemmyError> {
386 let form = EmailVerificationForm {
387 local_user_id: user.local_user.id,
388 email: new_email.to_string(),
389 verification_token: generate_random_string(),
391 let verify_link = format!(
392 "{}/verify_email/{}",
393 settings.get_protocol_and_hostname(),
394 &form.verification_token
396 EmailVerification::create(pool, &form).await?;
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)?;
406 pub fn send_email_verification_success(
407 user: &LocalUserView,
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)
417 pub fn get_interface_language(user: &LocalUserView) -> Lang {
418 lang_str_to_lang(&user.local_user.interface_language)
421 pub fn get_interface_language_from_settings(user: &LocalUserSettingsView) -> Lang {
422 lang_str_to_lang(&user.local_user.interface_language)
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")
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;
439 message_per_second: l.message_per_second,
441 post_per_second: l.post_per_second,
442 register: l.register,
443 register_per_second: l.register_per_second,
445 image_per_second: l.image_per_second,
447 comment_per_second: l.comment_per_second,
449 search_per_second: l.search_per_second,
453 pub fn local_site_to_slur_regex(local_site: &LocalSite) -> Option<Regex> {
454 build_slur_regex(local_site.slur_filter_regex.as_deref())
457 pub fn local_site_opt_to_slur_regex(local_site: &Option<LocalSite>) -> Option<Regex> {
460 .map(local_site_to_slur_regex)
464 pub fn send_application_approved_email(
465 user: &LocalUserView,
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)
475 /// Send a new applicant email notification to all admins
476 pub async fn send_new_applicant_email_to_admins(
477 applicant_username: &str,
480 ) -> Result<(), LemmyError> {
481 // Collect the admins with emails
482 let admins = LocalUserSettingsView::list_admins_with_emails(pool).await?;
484 let applications_link = &format!(
485 "{}/registration_applications",
486 settings.get_protocol_and_hostname(),
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)?;
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,
505 ) -> Result<(), LemmyError> {
506 // Collect the admins with emails
507 let admins = LocalUserSettingsView::list_admins_with_emails(pool).await?;
509 let reports_link = &format!("{}/reports", settings.get_protocol_and_hostname(),);
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)?;
521 pub async fn check_registration_application(
522 local_user_view: &LocalUserView,
523 local_site: &LocalSite,
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
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(®istration_denied_message));
538 return Err(LemmyError::from_message("registration_application_pending"));
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.",
555 pub async fn purge_image_posts_for_person(
556 banned_person_id: PersonId,
559 client: &ClientWithMiddleware,
560 ) -> Result<(), LemmyError> {
561 let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
563 if let Some(url) = post.url {
564 purge_image_from_pictrs(client, settings, &url).await.ok();
566 if let Some(thumbnail_url) = post.thumbnail_url {
567 purge_image_from_pictrs(client, settings, &thumbnail_url)
573 Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
578 pub async fn purge_image_posts_for_community(
579 banned_community_id: CommunityId,
582 client: &ClientWithMiddleware,
583 ) -> Result<(), LemmyError> {
584 let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?;
586 if let Some(url) = post.url {
587 purge_image_from_pictrs(client, settings, &url).await.ok();
589 if let Some(thumbnail_url) = post.thumbnail_url {
590 purge_image_from_pictrs(client, settings, &thumbnail_url)
596 Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?;
601 pub async fn remove_user_data(
602 banned_person_id: PersonId,
605 client: &ClientWithMiddleware,
606 ) -> Result<(), LemmyError> {
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)
614 if let Some(banner) = person.banner {
615 purge_image_from_pictrs(client, settings, &banner)
620 // Update the fields to None
624 &PersonUpdateForm::builder()
632 Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
635 purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
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?;
642 // Filter to only this banned users top communities
643 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
645 .filter(|fmc| fmc.moderator.id == banned_person_id)
648 for first_mod_community in banned_user_first_communities {
649 let community_id = first_mod_community.community.id;
653 &CommunityUpdateForm::builder().removed(Some(true)).build(),
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();
661 if let Some(banner) = first_mod_community.community.banner {
662 purge_image_from_pictrs(client, settings, &banner)
666 // Update the fields to None
670 &CommunityUpdateForm::builder()
679 Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
684 pub async fn remove_user_data_in_community(
685 community_id: CommunityId,
686 banned_person_id: PersonId,
688 ) -> Result<(), LemmyError> {
690 Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
693 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
694 let comments = CommentQuery::builder()
696 .creator_id(Some(banned_person_id))
697 .community_id(Some(community_id))
698 .limit(Some(i64::MAX))
703 for comment_view in &comments {
704 let comment_id = comment_view.comment.id;
708 &CommentUpdateForm::builder().removed(Some(true)).build(),
716 pub async fn delete_user_account(
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)
729 if let Some(banner) = person.banner {
730 purge_image_from_pictrs(client, settings, &banner)
734 // No need to update avatar and banner, those are handled in Person::delete_account
737 Comment::permadelete_for_creator(pool, person_id)
739 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
742 Post::permadelete_for_creator(pool, person_id)
744 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
747 purge_image_posts_for_person(person_id, pool, settings, client).await?;
749 Person::delete_account(pool, person_id).await?;
754 pub fn listing_type_with_site_default(
755 listing_type: Option<ListingType>,
756 local_site: &LocalSite,
757 ) -> Result<ListingType, LemmyError> {
758 Ok(listing_type.unwrap_or(ListingType::from_str(
759 &local_site.default_post_listing_type,
765 use crate::utils::{honeypot_check, password_length_check};
769 fn password_length() {
770 assert!(password_length_check("Õ¼¾°3yË,o¸ãtÌÈú|ÇÁÙAøüÒI©·¤(T]/ð>æºWæ[C¤bªWöaÃÎñ·{=û³&§½K/c").is_ok());
771 assert!(password_length_check("1234567890").is_ok());
772 assert!(password_length_check("short").is_err());
773 assert!(password_length_check("looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong").is_err());
778 assert!(honeypot_check(&None).is_ok());
779 assert!(honeypot_check(&Some(String::new())).is_ok());
780 assert!(honeypot_check(&Some("1".to_string())).is_err());
781 assert!(honeypot_check(&Some("message".to_string())).is_err());
785 pub enum EndpointType {
793 /// Generates an apub endpoint for a given domain, IE xyz.tld
794 pub fn generate_local_apub_endpoint(
795 endpoint_type: EndpointType,
798 ) -> Result<DbUrl, ParseError> {
799 let point = match endpoint_type {
800 EndpointType::Community => "c",
801 EndpointType::Person => "u",
802 EndpointType::Post => "post",
803 EndpointType::Comment => "comment",
804 EndpointType::PrivateMessage => "private_message",
807 Ok(Url::parse(&format!("{domain}/{point}/{name}"))?.into())
810 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
811 Ok(Url::parse(&format!("{actor_id}/followers"))?.into())
814 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
815 Ok(Url::parse(&format!("{actor_id}/inbox"))?.into())
818 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
819 let mut actor_id: Url = actor_id.clone().into();
820 actor_id.set_path("site_inbox");
824 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
825 let actor_id: Url = actor_id.clone().into();
829 &actor_id.host_str().context(location_info!())?,
830 if let Some(port) = actor_id.port() {
836 Ok(Url::parse(&url)?.into())
839 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
840 Ok(Url::parse(&format!("{actor_id}/outbox"))?.into())
843 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
844 Ok(Url::parse(&format!("{community_id}/moderators"))?.into())