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, CommunityModerator, 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},
24 use lemmy_db_views::{comment_view::CommentQuery, structs::LocalUserView};
25 use lemmy_db_views_actor::structs::{
26 CommunityModeratorView,
27 CommunityPersonBanView,
33 email::{send_email, translations::Lang},
36 rate_limit::RateLimitConfig,
37 settings::structs::Settings,
38 utils::slurs::build_slur_regex,
41 use reqwest_middleware::ClientWithMiddleware;
42 use rosetta_i18n::{Language, LanguageId};
44 use url::{ParseError, Url};
46 #[tracing::instrument(skip_all)]
47 pub async fn is_mod_or_admin(
50 community_id: CommunityId,
51 ) -> Result<(), LemmyError> {
52 let is_mod_or_admin = CommunityView::is_mod_or_admin(pool, person_id, community_id).await?;
54 return Err(LemmyError::from_message("not_a_mod_or_admin"));
59 #[tracing::instrument(skip_all)]
60 pub async fn is_mod_or_admin_opt(
62 local_user_view: Option<&LocalUserView>,
63 community_id: Option<CommunityId>,
64 ) -> Result<(), LemmyError> {
65 if let Some(local_user_view) = local_user_view {
66 if let Some(community_id) = community_id {
67 is_mod_or_admin(pool, local_user_view.person.id, community_id).await
69 is_admin(local_user_view)
72 Err(LemmyError::from_message("not_a_mod_or_admin"))
76 pub async fn is_top_admin(pool: &DbPool, person_id: PersonId) -> Result<(), LemmyError> {
77 let admins = PersonView::admins(pool).await?;
78 let top_admin = admins
80 .ok_or_else(|| LemmyError::from_message("no admins"))?;
82 if top_admin.person.id != person_id {
83 return Err(LemmyError::from_message("not_top_admin"));
88 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
89 if !local_user_view.person.admin {
90 return Err(LemmyError::from_message("not_an_admin"));
96 local_user_view: &LocalUserView,
97 community_mods: &[CommunityModeratorView],
98 ) -> Result<(), LemmyError> {
99 if local_user_view.person.id
102 .map(|cm| cm.moderator.id)
103 .unwrap_or(PersonId(0))
105 return Err(LemmyError::from_message("not_top_mod"));
110 #[tracing::instrument(skip_all)]
111 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
112 Post::read(pool, post_id)
114 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))
117 #[tracing::instrument(skip_all)]
118 pub async fn mark_post_as_read(
122 ) -> Result<PostRead, LemmyError> {
123 let post_read_form = PostReadForm { post_id, person_id };
125 PostRead::mark_as_read(pool, &post_read_form)
127 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
130 #[tracing::instrument(skip_all)]
131 pub async fn mark_post_as_unread(
135 ) -> Result<usize, LemmyError> {
136 let post_read_form = PostReadForm { post_id, person_id };
138 PostRead::mark_as_unread(pool, &post_read_form)
140 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
143 // TODO: this should simply take LemmyContext as param
144 #[tracing::instrument(skip_all)]
145 pub async fn get_local_user_view_from_jwt(
149 ) -> Result<LocalUserView, LemmyError> {
150 let claims = Claims::decode(jwt, &secret.jwt_secret)
151 .map_err(|e| e.with_message("not_logged_in"))?
153 let local_user_id = LocalUserId(claims.sub);
154 let local_user_view = LocalUserView::read(pool, local_user_id).await?;
156 local_user_view.person.banned,
157 local_user_view.person.ban_expires,
158 local_user_view.person.deleted,
161 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
166 /// Checks if user's token was issued before user's password reset.
167 pub fn check_validator_time(
168 validator_time: &NaiveDateTime,
170 ) -> Result<(), LemmyError> {
171 let user_validation_time = validator_time.timestamp();
172 if user_validation_time > claims.iat {
173 Err(LemmyError::from_message("not_logged_in"))
179 #[tracing::instrument(skip_all)]
180 pub async fn get_local_user_view_from_jwt_opt(
181 jwt: Option<&Sensitive<String>>,
184 ) -> Result<Option<LocalUserView>, LemmyError> {
186 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
191 #[tracing::instrument(skip_all)]
192 pub async fn get_local_user_settings_view_from_jwt_opt(
193 jwt: Option<&Sensitive<String>>,
196 ) -> Result<Option<LocalUserView>, LemmyError> {
199 let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
200 .map_err(|e| e.with_message("not_logged_in"))?
202 let local_user_id = LocalUserId(claims.sub);
203 let local_user_view = LocalUserView::read(pool, local_user_id).await?;
205 local_user_view.person.banned,
206 local_user_view.person.ban_expires,
207 local_user_view.person.deleted,
210 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
212 Ok(Some(local_user_view))
217 pub fn check_user_valid(
219 ban_expires: Option<NaiveDateTime>,
221 ) -> Result<(), LemmyError> {
222 // Check for a site ban
223 if is_banned(banned, ban_expires) {
224 return Err(LemmyError::from_message("site_ban"));
227 // check for account deletion
229 return Err(LemmyError::from_message("deleted"));
235 #[tracing::instrument(skip_all)]
236 pub async fn check_community_ban(
238 community_id: CommunityId,
240 ) -> Result<(), LemmyError> {
241 let is_banned = CommunityPersonBanView::get(pool, person_id, community_id)
245 Err(LemmyError::from_message("community_ban"))
251 #[tracing::instrument(skip_all)]
252 pub async fn check_community_deleted_or_removed(
253 community_id: CommunityId,
255 ) -> Result<(), LemmyError> {
256 let community = Community::read(pool, community_id)
258 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
259 if community.deleted || community.removed {
260 Err(LemmyError::from_message("deleted"))
266 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
267 if post.deleted || post.removed {
268 Err(LemmyError::from_message("deleted"))
274 #[tracing::instrument(skip_all)]
275 pub async fn check_person_block(
277 potential_blocker_id: PersonId,
279 ) -> Result<(), LemmyError> {
280 let is_blocked = PersonBlock::read(pool, potential_blocker_id, my_id)
284 Err(LemmyError::from_message("person_block"))
290 #[tracing::instrument(skip_all)]
291 pub fn check_downvotes_enabled(score: i16, local_site: &LocalSite) -> Result<(), LemmyError> {
292 if score == -1 && !local_site.enable_downvotes {
293 return Err(LemmyError::from_message("downvotes_disabled"));
298 #[tracing::instrument(skip_all)]
299 pub fn check_private_instance(
300 local_user_view: &Option<LocalUserView>,
301 local_site: &LocalSite,
302 ) -> Result<(), LemmyError> {
303 if local_user_view.is_none() && local_site.private_instance {
304 return Err(LemmyError::from_message("instance_is_private"));
309 #[tracing::instrument(skip_all)]
310 pub async fn build_federated_instances(
311 local_site: &LocalSite,
313 ) -> Result<Option<FederatedInstances>, LemmyError> {
314 if local_site.federation_enabled {
315 // TODO I hate that this requires 3 queries
316 let linked = Instance::linked(pool).await?;
317 let allowed = Instance::allowlist(pool).await?;
318 let blocked = Instance::blocklist(pool).await?;
320 // These can return empty vectors, so convert them to options
321 let allowed = (!allowed.is_empty()).then_some(allowed);
322 let blocked = (!blocked.is_empty()).then_some(blocked);
324 Ok(Some(FederatedInstances {
334 /// Checks the password length
335 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
336 if !(10..=60).contains(&pass.chars().count()) {
337 Err(LemmyError::from_message("invalid_password"))
343 /// Checks the site description length
344 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
345 if description.len() > 150 {
346 Err(LemmyError::from_message("site_description_length_overflow"))
352 /// Checks for a honeypot. If this field is filled, fail the rest of the function
353 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
354 if honeypot.is_some() && honeypot != &Some(String::new()) {
355 Err(LemmyError::from_message("honeypot_fail"))
361 pub fn send_email_to_user(
362 local_user_view: &LocalUserView,
367 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
371 if let Some(user_email) = &local_user_view.local_user.email {
375 &local_user_view.person.name,
380 Err(e) => warn!("{}", e),
385 pub async fn send_password_reset_email(
386 user: &LocalUserView,
389 ) -> Result<(), LemmyError> {
390 // Generate a random token
391 let token = uuid::Uuid::new_v4().to_string();
394 let token2 = token.clone();
395 let local_user_id = user.local_user.id;
396 PasswordResetRequest::create_token(pool, local_user_id, &token2).await?;
398 let email = &user.local_user.email.clone().expect("email");
399 let lang = get_interface_language(user);
400 let subject = &lang.password_reset_subject(&user.person.name);
401 let protocol_and_hostname = settings.get_protocol_and_hostname();
402 let reset_link = format!("{}/password_change/{}", protocol_and_hostname, &token);
403 let body = &lang.password_reset_body(reset_link, &user.person.name);
404 send_email(subject, email, &user.person.name, body, settings)
407 /// Send a verification email
408 pub async fn send_verification_email(
409 user: &LocalUserView,
413 ) -> Result<(), LemmyError> {
414 let form = EmailVerificationForm {
415 local_user_id: user.local_user.id,
416 email: new_email.to_string(),
417 verification_token: uuid::Uuid::new_v4().to_string(),
419 let verify_link = format!(
420 "{}/verify_email/{}",
421 settings.get_protocol_and_hostname(),
422 &form.verification_token
424 EmailVerification::create(pool, &form).await?;
426 let lang = get_interface_language(user);
427 let subject = lang.verify_email_subject(&settings.hostname);
428 let body = lang.verify_email_body(&settings.hostname, &user.person.name, verify_link);
429 send_email(&subject, new_email, &user.person.name, &body, settings)?;
434 pub fn send_email_verification_success(
435 user: &LocalUserView,
437 ) -> Result<(), LemmyError> {
438 let email = &user.local_user.email.clone().expect("email");
439 let lang = get_interface_language(user);
440 let subject = &lang.email_verified_subject(&user.person.actor_id);
441 let body = &lang.email_verified_body();
442 send_email(subject, email, &user.person.name, body, settings)
445 pub fn get_interface_language(user: &LocalUserView) -> Lang {
446 lang_str_to_lang(&user.local_user.interface_language)
449 pub fn get_interface_language_from_settings(user: &LocalUserView) -> Lang {
450 lang_str_to_lang(&user.local_user.interface_language)
453 fn lang_str_to_lang(lang: &str) -> Lang {
454 let lang_id = LanguageId::new(lang);
455 Lang::from_language_id(&lang_id).unwrap_or_else(|| {
456 let en = LanguageId::new("en");
457 Lang::from_language_id(&en).expect("default language")
461 pub fn local_site_rate_limit_to_rate_limit_config(
462 local_site_rate_limit: &LocalSiteRateLimit,
463 ) -> RateLimitConfig {
464 let l = local_site_rate_limit;
467 message_per_second: l.message_per_second,
469 post_per_second: l.post_per_second,
470 register: l.register,
471 register_per_second: l.register_per_second,
473 image_per_second: l.image_per_second,
475 comment_per_second: l.comment_per_second,
477 search_per_second: l.search_per_second,
481 pub fn local_site_to_slur_regex(local_site: &LocalSite) -> Option<Regex> {
482 build_slur_regex(local_site.slur_filter_regex.as_deref())
485 pub fn local_site_opt_to_slur_regex(local_site: &Option<LocalSite>) -> Option<Regex> {
488 .map(local_site_to_slur_regex)
492 pub fn send_application_approved_email(
493 user: &LocalUserView,
495 ) -> Result<(), LemmyError> {
496 let email = &user.local_user.email.clone().expect("email");
497 let lang = get_interface_language(user);
498 let subject = lang.registration_approved_subject(&user.person.actor_id);
499 let body = lang.registration_approved_body(&settings.hostname);
500 send_email(&subject, email, &user.person.name, &body, settings)
503 /// Send a new applicant email notification to all admins
504 pub async fn send_new_applicant_email_to_admins(
505 applicant_username: &str,
508 ) -> Result<(), LemmyError> {
509 // Collect the admins with emails
510 let admins = LocalUserView::list_admins_with_emails(pool).await?;
512 let applications_link = &format!(
513 "{}/registration_applications",
514 settings.get_protocol_and_hostname(),
517 for admin in &admins {
518 let email = &admin.local_user.email.clone().expect("email");
519 let lang = get_interface_language_from_settings(admin);
520 let subject = lang.new_application_subject(&settings.hostname, applicant_username);
521 let body = lang.new_application_body(applications_link);
522 send_email(&subject, email, &admin.person.name, &body, settings)?;
527 /// Send a report to all admins
528 pub async fn send_new_report_email_to_admins(
529 reporter_username: &str,
530 reported_username: &str,
533 ) -> Result<(), LemmyError> {
534 // Collect the admins with emails
535 let admins = LocalUserView::list_admins_with_emails(pool).await?;
537 let reports_link = &format!("{}/reports", settings.get_protocol_and_hostname(),);
539 for admin in &admins {
540 let email = &admin.local_user.email.clone().expect("email");
541 let lang = get_interface_language_from_settings(admin);
542 let subject = lang.new_report_subject(&settings.hostname, reporter_username, reported_username);
543 let body = lang.new_report_body(reports_link);
544 send_email(&subject, email, &admin.person.name, &body, settings)?;
549 pub async fn check_registration_application(
550 local_user_view: &LocalUserView,
551 local_site: &LocalSite,
553 ) -> Result<(), LemmyError> {
554 if local_site.registration_mode == RegistrationMode::RequireApplication
555 && !local_user_view.local_user.accepted_application
556 && !local_user_view.person.admin
558 // Fetch the registration, see if its denied
559 let local_user_id = local_user_view.local_user.id;
560 let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?;
561 if let Some(deny_reason) = registration.deny_reason {
562 let lang = get_interface_language(local_user_view);
563 let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason);
564 return Err(LemmyError::from_message(®istration_denied_message));
566 return Err(LemmyError::from_message("registration_application_pending"));
572 pub fn check_private_instance_and_federation_enabled(
573 local_site: &LocalSite,
574 ) -> Result<(), LemmyError> {
575 if local_site.private_instance && local_site.federation_enabled {
576 return Err(LemmyError::from_message(
577 "Cannot have both private instance and federation enabled.",
583 pub async fn purge_image_posts_for_person(
584 banned_person_id: PersonId,
587 client: &ClientWithMiddleware,
588 ) -> Result<(), LemmyError> {
589 let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
591 if let Some(url) = post.url {
592 purge_image_from_pictrs(client, settings, &url).await.ok();
594 if let Some(thumbnail_url) = post.thumbnail_url {
595 purge_image_from_pictrs(client, settings, &thumbnail_url)
601 Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
606 pub async fn purge_image_posts_for_community(
607 banned_community_id: CommunityId,
610 client: &ClientWithMiddleware,
611 ) -> Result<(), LemmyError> {
612 let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?;
614 if let Some(url) = post.url {
615 purge_image_from_pictrs(client, settings, &url).await.ok();
617 if let Some(thumbnail_url) = post.thumbnail_url {
618 purge_image_from_pictrs(client, settings, &thumbnail_url)
624 Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?;
629 pub async fn remove_user_data(
630 banned_person_id: PersonId,
633 client: &ClientWithMiddleware,
634 ) -> Result<(), LemmyError> {
636 let person = Person::read(pool, banned_person_id).await?;
637 if let Some(avatar) = person.avatar {
638 purge_image_from_pictrs(client, settings, &avatar)
642 if let Some(banner) = person.banner {
643 purge_image_from_pictrs(client, settings, &banner)
648 // Update the fields to None
652 &PersonUpdateForm::builder()
660 Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
663 purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
666 // Remove all communities where they're the top mod
667 // for now, remove the communities manually
668 let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
670 // Filter to only this banned users top communities
671 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
673 .filter(|fmc| fmc.moderator.id == banned_person_id)
676 for first_mod_community in banned_user_first_communities {
677 let community_id = first_mod_community.community.id;
681 &CommunityUpdateForm::builder().removed(Some(true)).build(),
685 // Delete the community images
686 if let Some(icon) = first_mod_community.community.icon {
687 purge_image_from_pictrs(client, settings, &icon).await.ok();
689 if let Some(banner) = first_mod_community.community.banner {
690 purge_image_from_pictrs(client, settings, &banner)
694 // Update the fields to None
698 &CommunityUpdateForm::builder()
707 Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
712 pub async fn remove_user_data_in_community(
713 community_id: CommunityId,
714 banned_person_id: PersonId,
716 ) -> Result<(), LemmyError> {
718 Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
721 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
722 let comments = CommentQuery::builder()
724 .creator_id(Some(banned_person_id))
725 .community_id(Some(community_id))
726 .limit(Some(i64::MAX))
731 for comment_view in &comments {
732 let comment_id = comment_view.comment.id;
736 &CommentUpdateForm::builder().removed(Some(true)).build(),
744 pub async fn delete_user_account(
748 client: &ClientWithMiddleware,
749 ) -> Result<(), LemmyError> {
750 // Delete their images
751 let person = Person::read(pool, person_id).await?;
752 if let Some(avatar) = person.avatar {
753 purge_image_from_pictrs(client, settings, &avatar)
757 if let Some(banner) = person.banner {
758 purge_image_from_pictrs(client, settings, &banner)
762 // No need to update avatar and banner, those are handled in Person::delete_account
765 Comment::permadelete_for_creator(pool, person_id)
767 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
770 Post::permadelete_for_creator(pool, person_id)
772 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
775 purge_image_posts_for_person(person_id, pool, settings, client).await?;
777 // Leave communities they mod
778 CommunityModerator::leave_all_communities(pool, person_id).await?;
780 Person::delete_account(pool, person_id).await?;
787 use crate::utils::{honeypot_check, password_length_check};
791 fn password_length() {
792 assert!(password_length_check("Õ¼¾°3yË,o¸ãtÌÈú|ÇÁÙAøüÒI©·¤(T]/ð>æºWæ[C¤bªWöaÃÎñ·{=û³&§½K/c").is_ok());
793 assert!(password_length_check("1234567890").is_ok());
794 assert!(password_length_check("short").is_err());
795 assert!(password_length_check("looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong").is_err());
800 assert!(honeypot_check(&None).is_ok());
801 assert!(honeypot_check(&Some(String::new())).is_ok());
802 assert!(honeypot_check(&Some("1".to_string())).is_err());
803 assert!(honeypot_check(&Some("message".to_string())).is_err());
807 pub enum EndpointType {
815 /// Generates an apub endpoint for a given domain, IE xyz.tld
816 pub fn generate_local_apub_endpoint(
817 endpoint_type: EndpointType,
820 ) -> Result<DbUrl, ParseError> {
821 let point = match endpoint_type {
822 EndpointType::Community => "c",
823 EndpointType::Person => "u",
824 EndpointType::Post => "post",
825 EndpointType::Comment => "comment",
826 EndpointType::PrivateMessage => "private_message",
829 Ok(Url::parse(&format!("{domain}/{point}/{name}"))?.into())
832 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
833 Ok(Url::parse(&format!("{actor_id}/followers"))?.into())
836 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
837 Ok(Url::parse(&format!("{actor_id}/inbox"))?.into())
840 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
841 let mut actor_id: Url = actor_id.clone().into();
842 actor_id.set_path("site_inbox");
846 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
847 let actor_id: Url = actor_id.clone().into();
851 &actor_id.host_str().context(location_info!())?,
852 if let Some(port) = actor_id.port() {
858 Ok(Url::parse(&url)?.into())
861 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
862 Ok(Url::parse(&format!("{actor_id}/outbox"))?.into())
865 pub fn generate_featured_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
866 Ok(Url::parse(&format!("{actor_id}/featured"))?.into())
869 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
870 Ok(Url::parse(&format!("{community_id}/moderators"))?.into())