3 request::purge_image_from_pictrs,
5 site::FederatedInstances,
8 use chrono::NaiveDateTime;
10 impls::person::is_banned,
11 newtypes::{CommunityId, DbUrl, LocalUserId, PersonId, PostId},
13 comment::{Comment, CommentUpdateForm},
14 community::{Community, CommunityModerator, CommunityUpdateForm},
15 email_verification::{EmailVerification, EmailVerificationForm},
17 local_site::LocalSite,
18 local_site_rate_limit::LocalSiteRateLimit,
19 password_reset_request::PasswordResetRequest,
20 person::{Person, PersonUpdateForm},
21 person_block::PersonBlock,
22 post::{Post, PostRead, PostReadForm},
23 registration_application::RegistrationApplication,
25 traits::{Crud, Readable},
29 use lemmy_db_views::{comment_view::CommentQuery, structs::LocalUserView};
30 use lemmy_db_views_actor::structs::{
31 CommunityModeratorView,
32 CommunityPersonBanView,
37 email::{send_email, translations::Lang},
38 error::{LemmyError, LemmyErrorExt, LemmyErrorExt2, LemmyErrorType},
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};
48 use url::{ParseError, Url};
50 #[tracing::instrument(skip_all)]
51 pub async fn is_mod_or_admin(
52 pool: &mut DbPool<'_>,
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(LemmyErrorType::NotAModOrAdmin)?;
63 #[tracing::instrument(skip_all)]
64 pub async fn is_mod_or_admin_opt(
65 pool: &mut DbPool<'_>,
66 local_user_view: Option<&LocalUserView>,
67 community_id: Option<CommunityId>,
68 ) -> Result<(), LemmyError> {
69 if let Some(local_user_view) = local_user_view {
70 if let Some(community_id) = community_id {
71 is_mod_or_admin(pool, local_user_view.person.id, community_id).await
73 is_admin(local_user_view)
76 Err(LemmyErrorType::NotAModOrAdmin)?
80 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
81 if !local_user_view.person.admin {
82 Err(LemmyErrorType::NotAnAdmin)?;
88 local_user_view: &LocalUserView,
89 community_mods: &[CommunityModeratorView],
90 ) -> Result<(), LemmyError> {
91 if local_user_view.person.id
94 .map(|cm| cm.moderator.id)
95 .unwrap_or(PersonId(0))
97 Err(LemmyErrorType::NotTopMod)?;
102 #[tracing::instrument(skip_all)]
103 pub async fn get_post(post_id: PostId, pool: &mut DbPool<'_>) -> Result<Post, LemmyError> {
104 Post::read(pool, post_id)
106 .with_lemmy_type(LemmyErrorType::CouldntFindPost)
109 #[tracing::instrument(skip_all)]
110 pub async fn mark_post_as_read(
113 pool: &mut DbPool<'_>,
114 ) -> Result<PostRead, LemmyError> {
115 let post_read_form = PostReadForm { post_id, person_id };
117 PostRead::mark_as_read(pool, &post_read_form)
119 .with_lemmy_type(LemmyErrorType::CouldntMarkPostAsRead)
122 #[tracing::instrument(skip_all)]
123 pub async fn mark_post_as_unread(
126 pool: &mut DbPool<'_>,
127 ) -> Result<usize, LemmyError> {
128 let post_read_form = PostReadForm { post_id, person_id };
130 PostRead::mark_as_unread(pool, &post_read_form)
132 .with_lemmy_type(LemmyErrorType::CouldntMarkPostAsRead)
135 #[tracing::instrument(skip_all)]
136 pub async fn local_user_view_from_jwt(
138 context: &LemmyContext,
139 ) -> Result<LocalUserView, LemmyError> {
140 let claims = Claims::decode(jwt, &context.secret().jwt_secret)
141 .with_lemmy_type(LemmyErrorType::NotLoggedIn)?
143 let local_user_id = LocalUserId(claims.sub);
144 let local_user_view = LocalUserView::read(&mut context.pool(), local_user_id).await?;
146 local_user_view.person.banned,
147 local_user_view.person.ban_expires,
148 local_user_view.person.deleted,
151 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
156 #[tracing::instrument(skip_all)]
157 pub async fn local_user_view_from_jwt_opt(
158 jwt: Option<&Sensitive<String>>,
159 context: &LemmyContext,
160 ) -> Option<LocalUserView> {
161 local_user_view_from_jwt(jwt?, context).await.ok()
164 /// Checks if user's token was issued before user's password reset.
165 pub fn check_validator_time(
166 validator_time: &NaiveDateTime,
168 ) -> Result<(), LemmyError> {
169 let user_validation_time = validator_time.timestamp();
170 if user_validation_time > claims.iat {
171 Err(LemmyErrorType::NotLoggedIn)?
177 pub fn check_user_valid(
179 ban_expires: Option<NaiveDateTime>,
181 ) -> Result<(), LemmyError> {
182 // Check for a site ban
183 if is_banned(banned, ban_expires) {
184 Err(LemmyErrorType::SiteBan)?;
187 // check for account deletion
189 Err(LemmyErrorType::Deleted)?;
195 #[tracing::instrument(skip_all)]
196 pub async fn check_community_ban(
198 community_id: CommunityId,
199 pool: &mut DbPool<'_>,
200 ) -> Result<(), LemmyError> {
201 let is_banned = CommunityPersonBanView::get(pool, person_id, community_id)
205 Err(LemmyErrorType::BannedFromCommunity)?
211 #[tracing::instrument(skip_all)]
212 pub async fn check_community_deleted_or_removed(
213 community_id: CommunityId,
214 pool: &mut DbPool<'_>,
215 ) -> Result<(), LemmyError> {
216 let community = Community::read(pool, community_id)
218 .with_lemmy_type(LemmyErrorType::CouldntFindCommunity)?;
219 if community.deleted || community.removed {
220 Err(LemmyErrorType::Deleted)?
226 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
227 if post.deleted || post.removed {
228 Err(LemmyErrorType::Deleted)?
234 #[tracing::instrument(skip_all)]
235 pub async fn check_person_block(
237 potential_blocker_id: PersonId,
238 pool: &mut DbPool<'_>,
239 ) -> Result<(), LemmyError> {
240 let is_blocked = PersonBlock::read(pool, potential_blocker_id, my_id)
244 Err(LemmyErrorType::PersonIsBlocked)?
250 #[tracing::instrument(skip_all)]
251 pub fn check_downvotes_enabled(score: i16, local_site: &LocalSite) -> Result<(), LemmyError> {
252 if score == -1 && !local_site.enable_downvotes {
253 Err(LemmyErrorType::DownvotesAreDisabled)?;
258 #[tracing::instrument(skip_all)]
259 pub fn check_private_instance(
260 local_user_view: &Option<LocalUserView>,
261 local_site: &LocalSite,
262 ) -> Result<(), LemmyError> {
263 if local_user_view.is_none() && local_site.private_instance {
264 Err(LemmyErrorType::InstanceIsPrivate)?;
269 #[tracing::instrument(skip_all)]
270 pub async fn build_federated_instances(
271 local_site: &LocalSite,
272 pool: &mut DbPool<'_>,
273 ) -> Result<Option<FederatedInstances>, LemmyError> {
274 if local_site.federation_enabled {
275 // TODO I hate that this requires 3 queries
276 let (linked, allowed, blocked) = lemmy_db_schema::try_join_with_pool!(pool => (
282 Ok(Some(FederatedInstances {
292 /// Checks the password length
293 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
294 if !(10..=60).contains(&pass.chars().count()) {
295 Err(LemmyErrorType::InvalidPassword)?
301 /// Checks for a honeypot. If this field is filled, fail the rest of the function
302 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
303 if honeypot.is_some() && honeypot != &Some(String::new()) {
304 Err(LemmyErrorType::HoneypotFailed)?
310 pub async fn send_email_to_user(
311 local_user_view: &LocalUserView,
316 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
320 if let Some(user_email) = &local_user_view.local_user.email {
324 &local_user_view.person.name,
331 Err(e) => warn!("{}", e),
336 pub async fn send_password_reset_email(
337 user: &LocalUserView,
338 pool: &mut DbPool<'_>,
340 ) -> Result<(), LemmyError> {
341 // Generate a random token
342 let token = uuid::Uuid::new_v4().to_string();
345 let local_user_id = user.local_user.id;
346 PasswordResetRequest::create_token(pool, local_user_id, token.clone()).await?;
348 let email = &user.local_user.email.clone().expect("email");
349 let lang = get_interface_language(user);
350 let subject = &lang.password_reset_subject(&user.person.name);
351 let protocol_and_hostname = settings.get_protocol_and_hostname();
352 let reset_link = format!("{}/password_change/{}", protocol_and_hostname, &token);
353 let body = &lang.password_reset_body(reset_link, &user.person.name);
354 send_email(subject, email, &user.person.name, body, settings).await
357 /// Send a verification email
358 pub async fn send_verification_email(
359 user: &LocalUserView,
361 pool: &mut DbPool<'_>,
363 ) -> Result<(), LemmyError> {
364 let form = EmailVerificationForm {
365 local_user_id: user.local_user.id,
366 email: new_email.to_string(),
367 verification_token: uuid::Uuid::new_v4().to_string(),
369 let verify_link = format!(
370 "{}/verify_email/{}",
371 settings.get_protocol_and_hostname(),
372 &form.verification_token
374 EmailVerification::create(pool, &form).await?;
376 let lang = get_interface_language(user);
377 let subject = lang.verify_email_subject(&settings.hostname);
378 let body = lang.verify_email_body(&settings.hostname, &user.person.name, verify_link);
379 send_email(&subject, new_email, &user.person.name, &body, settings).await?;
384 pub fn get_interface_language(user: &LocalUserView) -> Lang {
385 lang_str_to_lang(&user.local_user.interface_language)
388 pub fn get_interface_language_from_settings(user: &LocalUserView) -> Lang {
389 lang_str_to_lang(&user.local_user.interface_language)
392 fn lang_str_to_lang(lang: &str) -> Lang {
393 let lang_id = LanguageId::new(lang);
394 Lang::from_language_id(&lang_id).unwrap_or_else(|| {
395 let en = LanguageId::new("en");
396 Lang::from_language_id(&en).expect("default language")
400 pub fn local_site_rate_limit_to_rate_limit_config(
401 local_site_rate_limit: &LocalSiteRateLimit,
402 ) -> RateLimitConfig {
403 let l = local_site_rate_limit;
406 message_per_second: l.message_per_second,
408 post_per_second: l.post_per_second,
409 register: l.register,
410 register_per_second: l.register_per_second,
412 image_per_second: l.image_per_second,
414 comment_per_second: l.comment_per_second,
416 search_per_second: l.search_per_second,
420 pub fn local_site_to_slur_regex(local_site: &LocalSite) -> Option<Regex> {
421 build_slur_regex(local_site.slur_filter_regex.as_deref())
424 pub fn local_site_opt_to_slur_regex(local_site: &Option<LocalSite>) -> Option<Regex> {
427 .map(local_site_to_slur_regex)
431 pub fn local_site_opt_to_sensitive(local_site: &Option<LocalSite>) -> bool {
434 .map(|site| site.enable_nsfw)
438 pub async fn send_application_approved_email(
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.registration_approved_subject(&user.person.actor_id);
445 let body = lang.registration_approved_body(&settings.hostname);
446 send_email(&subject, email, &user.person.name, &body, settings).await
449 /// Send a new applicant email notification to all admins
450 pub async fn send_new_applicant_email_to_admins(
451 applicant_username: &str,
452 pool: &mut DbPool<'_>,
454 ) -> Result<(), LemmyError> {
455 // Collect the admins with emails
456 let admins = LocalUserView::list_admins_with_emails(pool).await?;
458 let applications_link = &format!(
459 "{}/registration_applications",
460 settings.get_protocol_and_hostname(),
463 for admin in &admins {
464 let email = &admin.local_user.email.clone().expect("email");
465 let lang = get_interface_language_from_settings(admin);
466 let subject = lang.new_application_subject(&settings.hostname, applicant_username);
467 let body = lang.new_application_body(applications_link);
468 send_email(&subject, email, &admin.person.name, &body, settings).await?;
473 /// Send a report to all admins
474 pub async fn send_new_report_email_to_admins(
475 reporter_username: &str,
476 reported_username: &str,
477 pool: &mut DbPool<'_>,
479 ) -> Result<(), LemmyError> {
480 // Collect the admins with emails
481 let admins = LocalUserView::list_admins_with_emails(pool).await?;
483 let reports_link = &format!("{}/reports", settings.get_protocol_and_hostname(),);
485 for admin in &admins {
486 let email = &admin.local_user.email.clone().expect("email");
487 let lang = get_interface_language_from_settings(admin);
488 let subject = lang.new_report_subject(&settings.hostname, reported_username, reporter_username);
489 let body = lang.new_report_body(reports_link);
490 send_email(&subject, email, &admin.person.name, &body, settings).await?;
495 pub async fn check_registration_application(
496 local_user_view: &LocalUserView,
497 local_site: &LocalSite,
498 pool: &mut DbPool<'_>,
499 ) -> Result<(), LemmyError> {
500 if (local_site.registration_mode == RegistrationMode::RequireApplication
501 || local_site.registration_mode == RegistrationMode::Closed)
502 && !local_user_view.local_user.accepted_application
503 && !local_user_view.person.admin
505 // Fetch the registration, see if its denied
506 let local_user_id = local_user_view.local_user.id;
507 let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?;
508 if let Some(deny_reason) = registration.deny_reason {
509 let lang = get_interface_language(local_user_view);
510 let registration_denied_message = format!("{}: {}", lang.registration_denied(), deny_reason);
511 return Err(LemmyErrorType::RegistrationDenied(
512 registration_denied_message,
515 return Err(LemmyErrorType::RegistrationApplicationIsPending)?;
521 pub fn check_private_instance_and_federation_enabled(
522 local_site: &LocalSite,
523 ) -> Result<(), LemmyError> {
524 if local_site.private_instance && local_site.federation_enabled {
525 Err(LemmyErrorType::CantEnablePrivateInstanceAndFederationTogether)?;
530 pub async fn purge_image_posts_for_person(
531 banned_person_id: PersonId,
532 pool: &mut DbPool<'_>,
534 client: &ClientWithMiddleware,
535 ) -> Result<(), LemmyError> {
536 let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
538 if let Some(url) = post.url {
539 purge_image_from_pictrs(client, settings, &url).await.ok();
541 if let Some(thumbnail_url) = post.thumbnail_url {
542 purge_image_from_pictrs(client, settings, &thumbnail_url)
548 Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
553 pub async fn purge_image_posts_for_community(
554 banned_community_id: CommunityId,
555 pool: &mut DbPool<'_>,
557 client: &ClientWithMiddleware,
558 ) -> Result<(), LemmyError> {
559 let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?;
561 if let Some(url) = post.url {
562 purge_image_from_pictrs(client, settings, &url).await.ok();
564 if let Some(thumbnail_url) = post.thumbnail_url {
565 purge_image_from_pictrs(client, settings, &thumbnail_url)
571 Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?;
576 pub async fn remove_user_data(
577 banned_person_id: PersonId,
578 pool: &mut DbPool<'_>,
580 client: &ClientWithMiddleware,
581 ) -> Result<(), LemmyError> {
583 let person = Person::read(pool, banned_person_id).await?;
584 if let Some(avatar) = person.avatar {
585 purge_image_from_pictrs(client, settings, &avatar)
589 if let Some(banner) = person.banner {
590 purge_image_from_pictrs(client, settings, &banner)
595 // Update the fields to None
608 Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
611 purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
614 // Remove all communities where they're the top mod
615 // for now, remove the communities manually
616 let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
618 // Filter to only this banned users top communities
619 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
621 .filter(|fmc| fmc.moderator.id == banned_person_id)
624 for first_mod_community in banned_user_first_communities {
625 let community_id = first_mod_community.community.id;
629 &CommunityUpdateForm {
636 // Delete the community images
637 if let Some(icon) = first_mod_community.community.icon {
638 purge_image_from_pictrs(client, settings, &icon).await.ok();
640 if let Some(banner) = first_mod_community.community.banner {
641 purge_image_from_pictrs(client, settings, &banner)
645 // Update the fields to None
649 &CommunityUpdateForm {
659 Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
664 pub async fn remove_user_data_in_community(
665 community_id: CommunityId,
666 banned_person_id: PersonId,
667 pool: &mut DbPool<'_>,
668 ) -> Result<(), LemmyError> {
670 Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
673 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
674 let comments = CommentQuery {
675 creator_id: Some(banned_person_id),
676 community_id: Some(community_id),
682 for comment_view in &comments {
683 let comment_id = comment_view.comment.id;
698 pub async fn delete_user_account(
700 pool: &mut DbPool<'_>,
702 client: &ClientWithMiddleware,
703 ) -> Result<(), LemmyError> {
704 // Delete their images
705 let person = Person::read(pool, person_id).await?;
706 if let Some(avatar) = person.avatar {
707 purge_image_from_pictrs(client, settings, &avatar)
711 if let Some(banner) = person.banner {
712 purge_image_from_pictrs(client, settings, &banner)
716 // No need to update avatar and banner, those are handled in Person::delete_account
719 Comment::permadelete_for_creator(pool, person_id)
721 .with_lemmy_type(LemmyErrorType::CouldntUpdateComment)?;
724 Post::permadelete_for_creator(pool, person_id)
726 .with_lemmy_type(LemmyErrorType::CouldntUpdatePost)?;
729 purge_image_posts_for_person(person_id, pool, settings, client).await?;
731 // Leave communities they mod
732 CommunityModerator::leave_all_communities(pool, person_id).await?;
734 Person::delete_account(pool, person_id).await?;
739 pub enum EndpointType {
747 /// Generates an apub endpoint for a given domain, IE xyz.tld
748 pub fn generate_local_apub_endpoint(
749 endpoint_type: EndpointType,
752 ) -> Result<DbUrl, ParseError> {
753 let point = match endpoint_type {
754 EndpointType::Community => "c",
755 EndpointType::Person => "u",
756 EndpointType::Post => "post",
757 EndpointType::Comment => "comment",
758 EndpointType::PrivateMessage => "private_message",
761 Ok(Url::parse(&format!("{domain}/{point}/{name}"))?.into())
764 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
765 Ok(Url::parse(&format!("{actor_id}/followers"))?.into())
768 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
769 Ok(Url::parse(&format!("{actor_id}/inbox"))?.into())
772 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
773 let mut actor_id: Url = actor_id.clone().into();
774 actor_id.set_path("site_inbox");
778 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
779 let actor_id: Url = actor_id.clone().into();
783 &actor_id.host_str().context(location_info!())?,
784 if let Some(port) = actor_id.port() {
790 Ok(Url::parse(&url)?.into())
793 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
794 Ok(Url::parse(&format!("{actor_id}/outbox"))?.into())
797 pub fn generate_featured_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
798 Ok(Url::parse(&format!("{actor_id}/featured"))?.into())
801 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
802 Ok(Url::parse(&format!("{community_id}/moderators"))?.into())
805 /// Sanitize HTML with default options. Additionally, dont allow bypassing markdown
807 pub fn sanitize_html(data: &str) -> String {
808 ammonia::Builder::default()
809 .rm_tags(&["a", "img"])
812 // restore markdown quotes
813 .replace(">", ">")
814 // restore white space
815 .replace(" ", " ")
818 pub fn sanitize_html_opt(data: &Option<String>) -> Option<String> {
819 data.as_ref().map(|d| sanitize_html(d))
824 #![allow(clippy::unwrap_used)]
825 #![allow(clippy::indexing_slicing)]
827 use crate::utils::{honeypot_check, password_length_check, sanitize_html};
831 fn password_length() {
832 assert!(password_length_check("Õ¼¾°3yË,o¸ãtÌÈú|ÇÁÙAøüÒI©·¤(T]/ð>æºWæ[C¤bªWöaÃÎñ·{=û³&§½K/c").is_ok());
833 assert!(password_length_check("1234567890").is_ok());
834 assert!(password_length_check("short").is_err());
835 assert!(password_length_check("looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong").is_err());
840 assert!(honeypot_check(&None).is_ok());
841 assert!(honeypot_check(&Some(String::new())).is_ok());
842 assert!(honeypot_check(&Some("1".to_string())).is_err());
843 assert!(honeypot_check(&Some("message".to_string())).is_err());
847 fn test_sanitize_html() {
848 let sanitized = sanitize_html("<script>alert(1);</script> hello");
849 assert_eq!(sanitized, " hello");
850 let sanitized = sanitize_html("<img src='http://example.com'> test");
851 assert_eq!(sanitized, " test");
852 let sanitized = sanitize_html("Hello World");
853 assert_eq!(sanitized, "Hello World");