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,
39 email::{send_email, translations::Lang},
42 rate_limit::RateLimitConfig,
43 settings::structs::Settings,
44 utils::slurs::build_slur_regex,
47 use reqwest_middleware::ClientWithMiddleware;
48 use rosetta_i18n::{Language, LanguageId};
50 use url::{ParseError, Url};
52 #[tracing::instrument(skip_all)]
53 pub async fn is_mod_or_admin(
56 community_id: CommunityId,
57 ) -> Result<(), LemmyError> {
58 let is_mod_or_admin = CommunityView::is_mod_or_admin(pool, person_id, community_id).await?;
60 return Err(LemmyError::from_message("not_a_mod_or_admin"));
65 #[tracing::instrument(skip_all)]
66 pub async fn is_mod_or_admin_opt(
68 local_user_view: Option<&LocalUserView>,
69 community_id: Option<CommunityId>,
70 ) -> Result<(), LemmyError> {
71 if let Some(local_user_view) = local_user_view {
72 if let Some(community_id) = community_id {
73 is_mod_or_admin(pool, local_user_view.person.id, community_id).await
75 is_admin(local_user_view)
78 Err(LemmyError::from_message("not_a_mod_or_admin"))
82 pub async fn is_top_admin(pool: &DbPool, person_id: PersonId) -> Result<(), LemmyError> {
83 let admins = PersonView::admins(pool).await?;
84 let top_admin = admins
86 .ok_or_else(|| LemmyError::from_message("no admins"))?;
88 if top_admin.person.id != person_id {
89 return Err(LemmyError::from_message("not_top_admin"));
94 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
95 if !local_user_view.person.admin {
96 return Err(LemmyError::from_message("not_an_admin"));
102 local_user_view: &LocalUserView,
103 community_mods: &[CommunityModeratorView],
104 ) -> Result<(), LemmyError> {
105 if local_user_view.person.id
108 .map(|cm| cm.moderator.id)
109 .unwrap_or(PersonId(0))
111 return Err(LemmyError::from_message("not_top_mod"));
116 #[tracing::instrument(skip_all)]
117 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
118 Post::read(pool, post_id)
120 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))
123 #[tracing::instrument(skip_all)]
124 pub async fn mark_post_as_read(
128 ) -> Result<PostRead, LemmyError> {
129 let post_read_form = PostReadForm { post_id, person_id };
131 PostRead::mark_as_read(pool, &post_read_form)
133 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
136 #[tracing::instrument(skip_all)]
137 pub async fn mark_post_as_unread(
141 ) -> Result<usize, LemmyError> {
142 let post_read_form = PostReadForm { post_id, person_id };
144 PostRead::mark_as_unread(pool, &post_read_form)
146 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
149 #[tracing::instrument(skip_all)]
150 pub async fn local_user_view_from_jwt(
152 context: &LemmyContext,
153 ) -> Result<LocalUserView, LemmyError> {
154 let claims = Claims::decode(jwt, &context.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(context.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 #[tracing::instrument(skip_all)]
171 pub async fn local_user_view_from_jwt_opt(
172 jwt: Option<&Sensitive<String>>,
173 context: &LemmyContext,
174 ) -> Option<LocalUserView> {
175 local_user_view_from_jwt(jwt?, context).await.ok()
178 /// Checks if user's token was issued before user's password reset.
179 pub fn check_validator_time(
180 validator_time: &NaiveDateTime,
182 ) -> Result<(), LemmyError> {
183 let user_validation_time = validator_time.timestamp();
184 if user_validation_time > claims.iat {
185 Err(LemmyError::from_message("not_logged_in"))
191 pub fn check_user_valid(
193 ban_expires: Option<NaiveDateTime>,
195 ) -> Result<(), LemmyError> {
196 // Check for a site ban
197 if is_banned(banned, ban_expires) {
198 return Err(LemmyError::from_message("site_ban"));
201 // check for account deletion
203 return Err(LemmyError::from_message("deleted"));
209 #[tracing::instrument(skip_all)]
210 pub async fn check_community_ban(
212 community_id: CommunityId,
214 ) -> Result<(), LemmyError> {
215 let is_banned = CommunityPersonBanView::get(pool, person_id, community_id)
219 Err(LemmyError::from_message("community_ban"))
225 #[tracing::instrument(skip_all)]
226 pub async fn check_community_deleted_or_removed(
227 community_id: CommunityId,
229 ) -> Result<(), LemmyError> {
230 let community = Community::read(pool, community_id)
232 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
233 if community.deleted || community.removed {
234 Err(LemmyError::from_message("deleted"))
240 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
241 if post.deleted || post.removed {
242 Err(LemmyError::from_message("deleted"))
248 #[tracing::instrument(skip_all)]
249 pub async fn check_person_block(
251 potential_blocker_id: PersonId,
253 ) -> Result<(), LemmyError> {
254 let is_blocked = PersonBlock::read(pool, potential_blocker_id, my_id)
258 Err(LemmyError::from_message("person_block"))
264 #[tracing::instrument(skip_all)]
265 pub fn check_downvotes_enabled(score: i16, local_site: &LocalSite) -> Result<(), LemmyError> {
266 if score == -1 && !local_site.enable_downvotes {
267 return Err(LemmyError::from_message("downvotes_disabled"));
272 #[tracing::instrument(skip_all)]
273 pub fn check_private_instance(
274 local_user_view: &Option<LocalUserView>,
275 local_site: &LocalSite,
276 ) -> Result<(), LemmyError> {
277 if local_user_view.is_none() && local_site.private_instance {
278 return Err(LemmyError::from_message("instance_is_private"));
283 #[tracing::instrument(skip_all)]
284 pub async fn build_federated_instances(
285 local_site: &LocalSite,
287 ) -> Result<Option<FederatedInstances>, LemmyError> {
288 if local_site.federation_enabled {
289 // TODO I hate that this requires 3 queries
290 let (linked, allowed, blocked) = try_join!(
291 Instance::linked(pool),
292 Instance::allowlist(pool),
293 Instance::blocklist(pool)
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 = uuid::Uuid::new_v4().to_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: uuid::Uuid::new_v4().to_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 get_interface_language(user: &LocalUserView) -> Lang {
407 lang_str_to_lang(&user.local_user.interface_language)
410 pub fn get_interface_language_from_settings(user: &LocalUserView) -> Lang {
411 lang_str_to_lang(&user.local_user.interface_language)
414 fn lang_str_to_lang(lang: &str) -> Lang {
415 let lang_id = LanguageId::new(lang);
416 Lang::from_language_id(&lang_id).unwrap_or_else(|| {
417 let en = LanguageId::new("en");
418 Lang::from_language_id(&en).expect("default language")
422 pub fn local_site_rate_limit_to_rate_limit_config(
423 local_site_rate_limit: &LocalSiteRateLimit,
424 ) -> RateLimitConfig {
425 let l = local_site_rate_limit;
428 message_per_second: l.message_per_second,
430 post_per_second: l.post_per_second,
431 register: l.register,
432 register_per_second: l.register_per_second,
434 image_per_second: l.image_per_second,
436 comment_per_second: l.comment_per_second,
438 search_per_second: l.search_per_second,
442 pub fn local_site_to_slur_regex(local_site: &LocalSite) -> Option<Regex> {
443 build_slur_regex(local_site.slur_filter_regex.as_deref())
446 pub fn local_site_opt_to_slur_regex(local_site: &Option<LocalSite>) -> Option<Regex> {
449 .map(local_site_to_slur_regex)
453 pub fn send_application_approved_email(
454 user: &LocalUserView,
456 ) -> Result<(), LemmyError> {
457 let email = &user.local_user.email.clone().expect("email");
458 let lang = get_interface_language(user);
459 let subject = lang.registration_approved_subject(&user.person.actor_id);
460 let body = lang.registration_approved_body(&settings.hostname);
461 send_email(&subject, email, &user.person.name, &body, settings)
464 /// Send a new applicant email notification to all admins
465 pub async fn send_new_applicant_email_to_admins(
466 applicant_username: &str,
469 ) -> Result<(), LemmyError> {
470 // Collect the admins with emails
471 let admins = LocalUserView::list_admins_with_emails(pool).await?;
473 let applications_link = &format!(
474 "{}/registration_applications",
475 settings.get_protocol_and_hostname(),
478 for admin in &admins {
479 let email = &admin.local_user.email.clone().expect("email");
480 let lang = get_interface_language_from_settings(admin);
481 let subject = lang.new_application_subject(&settings.hostname, applicant_username);
482 let body = lang.new_application_body(applications_link);
483 send_email(&subject, email, &admin.person.name, &body, settings)?;
488 /// Send a report to all admins
489 pub async fn send_new_report_email_to_admins(
490 reporter_username: &str,
491 reported_username: &str,
494 ) -> Result<(), LemmyError> {
495 // Collect the admins with emails
496 let admins = LocalUserView::list_admins_with_emails(pool).await?;
498 let reports_link = &format!("{}/reports", settings.get_protocol_and_hostname(),);
500 for admin in &admins {
501 let email = &admin.local_user.email.clone().expect("email");
502 let lang = get_interface_language_from_settings(admin);
503 let subject = lang.new_report_subject(&settings.hostname, reporter_username, reported_username);
504 let body = lang.new_report_body(reports_link);
505 send_email(&subject, email, &admin.person.name, &body, settings)?;
510 pub async fn check_registration_application(
511 local_user_view: &LocalUserView,
512 local_site: &LocalSite,
514 ) -> Result<(), LemmyError> {
515 if (local_site.registration_mode == RegistrationMode::RequireApplication
516 || local_site.registration_mode == RegistrationMode::Closed)
517 && !local_user_view.local_user.accepted_application
518 && !local_user_view.person.admin
520 // Fetch the registration, see if its denied
521 let local_user_id = local_user_view.local_user.id;
522 let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?;
523 if let Some(deny_reason) = registration.deny_reason {
524 let lang = get_interface_language(local_user_view);
525 let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason);
526 return Err(LemmyError::from_message(®istration_denied_message));
528 return Err(LemmyError::from_message("registration_application_pending"));
534 pub fn check_private_instance_and_federation_enabled(
535 local_site: &LocalSite,
536 ) -> Result<(), LemmyError> {
537 if local_site.private_instance && local_site.federation_enabled {
538 return Err(LemmyError::from_message(
539 "Cannot have both private instance and federation enabled.",
545 pub async fn purge_image_posts_for_person(
546 banned_person_id: PersonId,
549 client: &ClientWithMiddleware,
550 ) -> Result<(), LemmyError> {
551 let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
553 if let Some(url) = post.url {
554 purge_image_from_pictrs(client, settings, &url).await.ok();
556 if let Some(thumbnail_url) = post.thumbnail_url {
557 purge_image_from_pictrs(client, settings, &thumbnail_url)
563 Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
568 pub async fn purge_image_posts_for_community(
569 banned_community_id: CommunityId,
572 client: &ClientWithMiddleware,
573 ) -> Result<(), LemmyError> {
574 let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?;
576 if let Some(url) = post.url {
577 purge_image_from_pictrs(client, settings, &url).await.ok();
579 if let Some(thumbnail_url) = post.thumbnail_url {
580 purge_image_from_pictrs(client, settings, &thumbnail_url)
586 Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?;
591 pub async fn remove_user_data(
592 banned_person_id: PersonId,
595 client: &ClientWithMiddleware,
596 ) -> Result<(), LemmyError> {
598 let person = Person::read(pool, banned_person_id).await?;
599 if let Some(avatar) = person.avatar {
600 purge_image_from_pictrs(client, settings, &avatar)
604 if let Some(banner) = person.banner {
605 purge_image_from_pictrs(client, settings, &banner)
610 // Update the fields to None
614 &PersonUpdateForm::builder()
622 Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
625 purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
628 // Remove all communities where they're the top mod
629 // for now, remove the communities manually
630 let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
632 // Filter to only this banned users top communities
633 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
635 .filter(|fmc| fmc.moderator.id == banned_person_id)
638 for first_mod_community in banned_user_first_communities {
639 let community_id = first_mod_community.community.id;
643 &CommunityUpdateForm::builder().removed(Some(true)).build(),
647 // Delete the community images
648 if let Some(icon) = first_mod_community.community.icon {
649 purge_image_from_pictrs(client, settings, &icon).await.ok();
651 if let Some(banner) = first_mod_community.community.banner {
652 purge_image_from_pictrs(client, settings, &banner)
656 // Update the fields to None
660 &CommunityUpdateForm::builder()
669 Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
674 pub async fn remove_user_data_in_community(
675 community_id: CommunityId,
676 banned_person_id: PersonId,
678 ) -> Result<(), LemmyError> {
680 Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
683 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
684 let comments = CommentQuery::builder()
686 .creator_id(Some(banned_person_id))
687 .community_id(Some(community_id))
688 .limit(Some(i64::MAX))
693 for comment_view in &comments {
694 let comment_id = comment_view.comment.id;
698 &CommentUpdateForm::builder().removed(Some(true)).build(),
706 pub async fn delete_user_account(
710 client: &ClientWithMiddleware,
711 ) -> Result<(), LemmyError> {
712 // Delete their images
713 let person = Person::read(pool, person_id).await?;
714 if let Some(avatar) = person.avatar {
715 purge_image_from_pictrs(client, settings, &avatar)
719 if let Some(banner) = person.banner {
720 purge_image_from_pictrs(client, settings, &banner)
724 // No need to update avatar and banner, those are handled in Person::delete_account
727 Comment::permadelete_for_creator(pool, person_id)
729 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
732 Post::permadelete_for_creator(pool, person_id)
734 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
737 purge_image_posts_for_person(person_id, pool, settings, client).await?;
739 // Leave communities they mod
740 CommunityModerator::leave_all_communities(pool, person_id).await?;
742 Person::delete_account(pool, person_id).await?;
749 use crate::utils::{honeypot_check, password_length_check};
753 fn password_length() {
754 assert!(password_length_check("Õ¼¾°3yË,o¸ãtÌÈú|ÇÁÙAøüÒI©·¤(T]/ð>æºWæ[C¤bªWöaÃÎñ·{=û³&§½K/c").is_ok());
755 assert!(password_length_check("1234567890").is_ok());
756 assert!(password_length_check("short").is_err());
757 assert!(password_length_check("looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong").is_err());
762 assert!(honeypot_check(&None).is_ok());
763 assert!(honeypot_check(&Some(String::new())).is_ok());
764 assert!(honeypot_check(&Some("1".to_string())).is_err());
765 assert!(honeypot_check(&Some("message".to_string())).is_err());
769 pub enum EndpointType {
777 /// Generates an apub endpoint for a given domain, IE xyz.tld
778 pub fn generate_local_apub_endpoint(
779 endpoint_type: EndpointType,
782 ) -> Result<DbUrl, ParseError> {
783 let point = match endpoint_type {
784 EndpointType::Community => "c",
785 EndpointType::Person => "u",
786 EndpointType::Post => "post",
787 EndpointType::Comment => "comment",
788 EndpointType::PrivateMessage => "private_message",
791 Ok(Url::parse(&format!("{domain}/{point}/{name}"))?.into())
794 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
795 Ok(Url::parse(&format!("{actor_id}/followers"))?.into())
798 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
799 Ok(Url::parse(&format!("{actor_id}/inbox"))?.into())
802 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
803 let mut actor_id: Url = actor_id.clone().into();
804 actor_id.set_path("site_inbox");
808 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
809 let actor_id: Url = actor_id.clone().into();
813 &actor_id.host_str().context(location_info!())?,
814 if let Some(port) = actor_id.port() {
820 Ok(Url::parse(&url)?.into())
823 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
824 Ok(Url::parse(&format!("{actor_id}/outbox"))?.into())
827 pub fn generate_featured_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
828 Ok(Url::parse(&format!("{actor_id}/featured"))?.into())
831 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
832 Ok(Url::parse(&format!("{community_id}/moderators"))?.into())