3 request::purge_image_from_pictrs,
5 site::FederatedInstances,
8 use chrono::NaiveDateTime;
10 use lemmy_db_schema::{
11 impls::person::is_banned,
12 newtypes::{CommunityId, DbUrl, LocalUserId, PersonId, PostId},
14 comment::{Comment, CommentUpdateForm},
15 community::{Community, CommunityModerator, CommunityUpdateForm},
16 email_verification::{EmailVerification, EmailVerificationForm},
18 local_site::LocalSite,
19 local_site_rate_limit::LocalSiteRateLimit,
20 password_reset_request::PasswordResetRequest,
21 person::{Person, PersonUpdateForm},
22 person_block::PersonBlock,
23 post::{Post, PostRead, PostReadForm},
24 registration_application::RegistrationApplication,
26 traits::{Crud, Readable},
30 use lemmy_db_views::{comment_view::CommentQuery, structs::LocalUserView};
31 use lemmy_db_views_actor::structs::{
32 CommunityModeratorView,
33 CommunityPersonBanView,
38 email::{send_email, translations::Lang},
39 error::{LemmyError, LemmyErrorExt, LemmyErrorExt2, LemmyErrorType},
41 rate_limit::RateLimitConfig,
42 settings::structs::Settings,
43 utils::slurs::build_slur_regex,
46 use reqwest_middleware::ClientWithMiddleware;
47 use rosetta_i18n::{Language, LanguageId};
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(LemmyErrorType::NotAModOrAdmin)?;
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(LemmyErrorType::NotAModOrAdmin)?
81 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
82 if !local_user_view.person.admin {
83 return Err(LemmyErrorType::NotAnAdmin)?;
89 local_user_view: &LocalUserView,
90 community_mods: &[CommunityModeratorView],
91 ) -> Result<(), LemmyError> {
92 if local_user_view.person.id
95 .map(|cm| cm.moderator.id)
96 .unwrap_or(PersonId(0))
98 return Err(LemmyErrorType::NotTopMod)?;
103 #[tracing::instrument(skip_all)]
104 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
105 Post::read(pool, post_id)
107 .with_lemmy_type(LemmyErrorType::CouldntFindPost)
110 #[tracing::instrument(skip_all)]
111 pub async fn mark_post_as_read(
115 ) -> Result<PostRead, LemmyError> {
116 let post_read_form = PostReadForm { post_id, person_id };
118 PostRead::mark_as_read(pool, &post_read_form)
120 .with_lemmy_type(LemmyErrorType::CouldntMarkPostAsRead)
123 #[tracing::instrument(skip_all)]
124 pub async fn mark_post_as_unread(
128 ) -> Result<usize, LemmyError> {
129 let post_read_form = PostReadForm { post_id, person_id };
131 PostRead::mark_as_unread(pool, &post_read_form)
133 .with_lemmy_type(LemmyErrorType::CouldntMarkPostAsRead)
136 #[tracing::instrument(skip_all)]
137 pub async fn local_user_view_from_jwt(
139 context: &LemmyContext,
140 ) -> Result<LocalUserView, LemmyError> {
141 let claims = Claims::decode(jwt, &context.secret().jwt_secret)
142 .with_lemmy_type(LemmyErrorType::NotLoggedIn)?
144 let local_user_id = LocalUserId(claims.sub);
145 let local_user_view = LocalUserView::read(context.pool(), local_user_id).await?;
147 local_user_view.person.banned,
148 local_user_view.person.ban_expires,
149 local_user_view.person.deleted,
152 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
157 #[tracing::instrument(skip_all)]
158 pub async fn local_user_view_from_jwt_opt(
159 jwt: Option<&Sensitive<String>>,
160 context: &LemmyContext,
161 ) -> Option<LocalUserView> {
162 local_user_view_from_jwt(jwt?, context).await.ok()
165 /// Checks if user's token was issued before user's password reset.
166 pub fn check_validator_time(
167 validator_time: &NaiveDateTime,
169 ) -> Result<(), LemmyError> {
170 let user_validation_time = validator_time.timestamp();
171 if user_validation_time > claims.iat {
172 Err(LemmyErrorType::NotLoggedIn)?
178 pub fn check_user_valid(
180 ban_expires: Option<NaiveDateTime>,
182 ) -> Result<(), LemmyError> {
183 // Check for a site ban
184 if is_banned(banned, ban_expires) {
185 return Err(LemmyErrorType::SiteBan)?;
188 // check for account deletion
190 return Err(LemmyErrorType::Deleted)?;
196 #[tracing::instrument(skip_all)]
197 pub async fn check_community_ban(
199 community_id: CommunityId,
201 ) -> Result<(), LemmyError> {
202 let is_banned = CommunityPersonBanView::get(pool, person_id, community_id)
206 Err(LemmyErrorType::BannedFromCommunity)?
212 #[tracing::instrument(skip_all)]
213 pub async fn check_community_deleted_or_removed(
214 community_id: CommunityId,
216 ) -> Result<(), LemmyError> {
217 let community = Community::read(pool, community_id)
219 .with_lemmy_type(LemmyErrorType::CouldntFindCommunity)?;
220 if community.deleted || community.removed {
221 Err(LemmyErrorType::Deleted)?
227 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
228 if post.deleted || post.removed {
229 Err(LemmyErrorType::Deleted)?
235 #[tracing::instrument(skip_all)]
236 pub async fn check_person_block(
238 potential_blocker_id: PersonId,
240 ) -> Result<(), LemmyError> {
241 let is_blocked = PersonBlock::read(pool, potential_blocker_id, my_id)
245 Err(LemmyErrorType::PersonIsBlocked)?
251 #[tracing::instrument(skip_all)]
252 pub fn check_downvotes_enabled(score: i16, local_site: &LocalSite) -> Result<(), LemmyError> {
253 if score == -1 && !local_site.enable_downvotes {
254 return Err(LemmyErrorType::DownvotesAreDisabled)?;
259 #[tracing::instrument(skip_all)]
260 pub fn check_private_instance(
261 local_user_view: &Option<LocalUserView>,
262 local_site: &LocalSite,
263 ) -> Result<(), LemmyError> {
264 if local_user_view.is_none() && local_site.private_instance {
265 return Err(LemmyErrorType::InstanceIsPrivate)?;
270 #[tracing::instrument(skip_all)]
271 pub async fn build_federated_instances(
272 local_site: &LocalSite,
274 ) -> Result<Option<FederatedInstances>, LemmyError> {
275 if local_site.federation_enabled {
276 // TODO I hate that this requires 3 queries
277 let (linked, allowed, blocked) = try_join!(
278 Instance::linked(pool),
279 Instance::allowlist(pool),
280 Instance::blocklist(pool)
283 Ok(Some(FederatedInstances {
293 /// Checks the password length
294 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
295 if !(10..=60).contains(&pass.chars().count()) {
296 Err(LemmyErrorType::InvalidPassword)?
302 /// Checks for a honeypot. If this field is filled, fail the rest of the function
303 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
304 if honeypot.is_some() && honeypot != &Some(String::new()) {
305 Err(LemmyErrorType::HoneypotFailed)?
311 pub async fn send_email_to_user(
312 local_user_view: &LocalUserView,
317 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
321 if let Some(user_email) = &local_user_view.local_user.email {
325 &local_user_view.person.name,
332 Err(e) => warn!("{}", e),
337 pub async fn send_password_reset_email(
338 user: &LocalUserView,
341 ) -> Result<(), LemmyError> {
342 // Generate a random token
343 let token = uuid::Uuid::new_v4().to_string();
346 let token2 = token.clone();
347 let local_user_id = user.local_user.id;
348 PasswordResetRequest::create_token(pool, local_user_id, &token2).await?;
350 let email = &user.local_user.email.clone().expect("email");
351 let lang = get_interface_language(user);
352 let subject = &lang.password_reset_subject(&user.person.name);
353 let protocol_and_hostname = settings.get_protocol_and_hostname();
354 let reset_link = format!("{}/password_change/{}", protocol_and_hostname, &token);
355 let body = &lang.password_reset_body(reset_link, &user.person.name);
356 send_email(subject, email, &user.person.name, body, settings).await
359 /// Send a verification email
360 pub async fn send_verification_email(
361 user: &LocalUserView,
365 ) -> Result<(), LemmyError> {
366 let form = EmailVerificationForm {
367 local_user_id: user.local_user.id,
368 email: new_email.to_string(),
369 verification_token: uuid::Uuid::new_v4().to_string(),
371 let verify_link = format!(
372 "{}/verify_email/{}",
373 settings.get_protocol_and_hostname(),
374 &form.verification_token
376 EmailVerification::create(pool, &form).await?;
378 let lang = get_interface_language(user);
379 let subject = lang.verify_email_subject(&settings.hostname);
380 let body = lang.verify_email_body(&settings.hostname, &user.person.name, verify_link);
381 send_email(&subject, new_email, &user.person.name, &body, settings).await?;
386 pub fn get_interface_language(user: &LocalUserView) -> Lang {
387 lang_str_to_lang(&user.local_user.interface_language)
390 pub fn get_interface_language_from_settings(user: &LocalUserView) -> Lang {
391 lang_str_to_lang(&user.local_user.interface_language)
394 fn lang_str_to_lang(lang: &str) -> Lang {
395 let lang_id = LanguageId::new(lang);
396 Lang::from_language_id(&lang_id).unwrap_or_else(|| {
397 let en = LanguageId::new("en");
398 Lang::from_language_id(&en).expect("default language")
402 pub fn local_site_rate_limit_to_rate_limit_config(
403 local_site_rate_limit: &LocalSiteRateLimit,
404 ) -> RateLimitConfig {
405 let l = local_site_rate_limit;
408 message_per_second: l.message_per_second,
410 post_per_second: l.post_per_second,
411 register: l.register,
412 register_per_second: l.register_per_second,
414 image_per_second: l.image_per_second,
416 comment_per_second: l.comment_per_second,
418 search_per_second: l.search_per_second,
422 pub fn local_site_to_slur_regex(local_site: &LocalSite) -> Option<Regex> {
423 build_slur_regex(local_site.slur_filter_regex.as_deref())
426 pub fn local_site_opt_to_slur_regex(local_site: &Option<LocalSite>) -> Option<Regex> {
429 .map(local_site_to_slur_regex)
433 pub fn local_site_opt_to_sensitive(local_site: &Option<LocalSite>) -> bool {
436 .map(|site| site.enable_nsfw)
440 pub async fn send_application_approved_email(
441 user: &LocalUserView,
443 ) -> Result<(), LemmyError> {
444 let email = &user.local_user.email.clone().expect("email");
445 let lang = get_interface_language(user);
446 let subject = lang.registration_approved_subject(&user.person.actor_id);
447 let body = lang.registration_approved_body(&settings.hostname);
448 send_email(&subject, email, &user.person.name, &body, settings).await
451 /// Send a new applicant email notification to all admins
452 pub async fn send_new_applicant_email_to_admins(
453 applicant_username: &str,
456 ) -> Result<(), LemmyError> {
457 // Collect the admins with emails
458 let admins = LocalUserView::list_admins_with_emails(pool).await?;
460 let applications_link = &format!(
461 "{}/registration_applications",
462 settings.get_protocol_and_hostname(),
465 for admin in &admins {
466 let email = &admin.local_user.email.clone().expect("email");
467 let lang = get_interface_language_from_settings(admin);
468 let subject = lang.new_application_subject(&settings.hostname, applicant_username);
469 let body = lang.new_application_body(applications_link);
470 send_email(&subject, email, &admin.person.name, &body, settings).await?;
475 /// Send a report to all admins
476 pub async fn send_new_report_email_to_admins(
477 reporter_username: &str,
478 reported_username: &str,
481 ) -> Result<(), LemmyError> {
482 // Collect the admins with emails
483 let admins = LocalUserView::list_admins_with_emails(pool).await?;
485 let reports_link = &format!("{}/reports", settings.get_protocol_and_hostname(),);
487 for admin in &admins {
488 let email = &admin.local_user.email.clone().expect("email");
489 let lang = get_interface_language_from_settings(admin);
490 let subject = lang.new_report_subject(&settings.hostname, reported_username, reporter_username);
491 let body = lang.new_report_body(reports_link);
492 send_email(&subject, email, &admin.person.name, &body, settings).await?;
497 pub async fn check_registration_application(
498 local_user_view: &LocalUserView,
499 local_site: &LocalSite,
501 ) -> Result<(), LemmyError> {
502 if (local_site.registration_mode == RegistrationMode::RequireApplication
503 || local_site.registration_mode == RegistrationMode::Closed)
504 && !local_user_view.local_user.accepted_application
505 && !local_user_view.person.admin
507 // Fetch the registration, see if its denied
508 let local_user_id = local_user_view.local_user.id;
509 let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?;
510 if let Some(deny_reason) = registration.deny_reason {
511 let lang = get_interface_language(local_user_view);
512 let registration_denied_message = format!("{}: {}", lang.registration_denied(), deny_reason);
513 return Err(LemmyErrorType::RegistrationDenied(
514 registration_denied_message,
517 return Err(LemmyErrorType::RegistrationApplicationIsPending)?;
523 pub fn check_private_instance_and_federation_enabled(
524 local_site: &LocalSite,
525 ) -> Result<(), LemmyError> {
526 if local_site.private_instance && local_site.federation_enabled {
527 return Err(LemmyErrorType::CantEnablePrivateInstanceAndFederationTogether)?;
532 pub async fn purge_image_posts_for_person(
533 banned_person_id: PersonId,
536 client: &ClientWithMiddleware,
537 ) -> Result<(), LemmyError> {
538 let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
540 if let Some(url) = post.url {
541 purge_image_from_pictrs(client, settings, &url).await.ok();
543 if let Some(thumbnail_url) = post.thumbnail_url {
544 purge_image_from_pictrs(client, settings, &thumbnail_url)
550 Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
555 pub async fn purge_image_posts_for_community(
556 banned_community_id: CommunityId,
559 client: &ClientWithMiddleware,
560 ) -> Result<(), LemmyError> {
561 let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_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_community(pool, banned_community_id).await?;
578 pub async fn remove_user_data(
579 banned_person_id: PersonId,
582 client: &ClientWithMiddleware,
583 ) -> Result<(), LemmyError> {
585 let person = Person::read(pool, banned_person_id).await?;
586 if let Some(avatar) = person.avatar {
587 purge_image_from_pictrs(client, settings, &avatar)
591 if let Some(banner) = person.banner {
592 purge_image_from_pictrs(client, settings, &banner)
597 // Update the fields to None
601 &PersonUpdateForm::builder()
609 Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
612 purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
615 // Remove all communities where they're the top mod
616 // for now, remove the communities manually
617 let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
619 // Filter to only this banned users top communities
620 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
622 .filter(|fmc| fmc.moderator.id == banned_person_id)
625 for first_mod_community in banned_user_first_communities {
626 let community_id = first_mod_community.community.id;
630 &CommunityUpdateForm::builder().removed(Some(true)).build(),
634 // Delete the community images
635 if let Some(icon) = first_mod_community.community.icon {
636 purge_image_from_pictrs(client, settings, &icon).await.ok();
638 if let Some(banner) = first_mod_community.community.banner {
639 purge_image_from_pictrs(client, settings, &banner)
643 // Update the fields to None
647 &CommunityUpdateForm::builder()
656 Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
661 pub async fn remove_user_data_in_community(
662 community_id: CommunityId,
663 banned_person_id: PersonId,
665 ) -> Result<(), LemmyError> {
667 Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
670 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
671 let comments = CommentQuery::builder()
673 .creator_id(Some(banned_person_id))
674 .community_id(Some(community_id))
679 for comment_view in &comments {
680 let comment_id = comment_view.comment.id;
684 &CommentUpdateForm::builder().removed(Some(true)).build(),
692 pub async fn delete_user_account(
696 client: &ClientWithMiddleware,
697 ) -> Result<(), LemmyError> {
698 // Delete their images
699 let person = Person::read(pool, person_id).await?;
700 if let Some(avatar) = person.avatar {
701 purge_image_from_pictrs(client, settings, &avatar)
705 if let Some(banner) = person.banner {
706 purge_image_from_pictrs(client, settings, &banner)
710 // No need to update avatar and banner, those are handled in Person::delete_account
713 Comment::permadelete_for_creator(pool, person_id)
715 .with_lemmy_type(LemmyErrorType::CouldntUpdateComment)?;
718 Post::permadelete_for_creator(pool, person_id)
720 .with_lemmy_type(LemmyErrorType::CouldntUpdatePost)?;
723 purge_image_posts_for_person(person_id, pool, settings, client).await?;
725 // Leave communities they mod
726 CommunityModerator::leave_all_communities(pool, person_id).await?;
728 Person::delete_account(pool, person_id).await?;
735 use crate::utils::{honeypot_check, password_length_check};
739 fn password_length() {
740 assert!(password_length_check("Õ¼¾°3yË,o¸ãtÌÈú|ÇÁÙAøüÒI©·¤(T]/ð>æºWæ[C¤bªWöaÃÎñ·{=û³&§½K/c").is_ok());
741 assert!(password_length_check("1234567890").is_ok());
742 assert!(password_length_check("short").is_err());
743 assert!(password_length_check("looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong").is_err());
748 assert!(honeypot_check(&None).is_ok());
749 assert!(honeypot_check(&Some(String::new())).is_ok());
750 assert!(honeypot_check(&Some("1".to_string())).is_err());
751 assert!(honeypot_check(&Some("message".to_string())).is_err());
755 pub enum EndpointType {
763 /// Generates an apub endpoint for a given domain, IE xyz.tld
764 pub fn generate_local_apub_endpoint(
765 endpoint_type: EndpointType,
768 ) -> Result<DbUrl, ParseError> {
769 let point = match endpoint_type {
770 EndpointType::Community => "c",
771 EndpointType::Person => "u",
772 EndpointType::Post => "post",
773 EndpointType::Comment => "comment",
774 EndpointType::PrivateMessage => "private_message",
777 Ok(Url::parse(&format!("{domain}/{point}/{name}"))?.into())
780 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
781 Ok(Url::parse(&format!("{actor_id}/followers"))?.into())
784 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
785 Ok(Url::parse(&format!("{actor_id}/inbox"))?.into())
788 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
789 let mut actor_id: Url = actor_id.clone().into();
790 actor_id.set_path("site_inbox");
794 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
795 let actor_id: Url = actor_id.clone().into();
799 &actor_id.host_str().context(location_info!())?,
800 if let Some(port) = actor_id.port() {
806 Ok(Url::parse(&url)?.into())
809 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
810 Ok(Url::parse(&format!("{actor_id}/outbox"))?.into())
813 pub fn generate_featured_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
814 Ok(Url::parse(&format!("{actor_id}/featured"))?.into())
817 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
818 Ok(Url::parse(&format!("{community_id}/moderators"))?.into())