8 use crate::site::FederatedInstances;
10 newtypes::{CommunityId, DbUrl, LocalUserId, PersonId, PostId},
14 email_verification::{EmailVerification, EmailVerificationForm},
15 password_reset_request::PasswordResetRequest,
17 person_block::PersonBlock,
18 post::{Post, PostRead, PostReadForm},
19 registration_application::RegistrationApplication,
23 traits::{Crud, Readable},
27 comment_view::CommentQueryBuilder,
28 local_user_view::{LocalUserSettingsView, LocalUserView},
30 use lemmy_db_views_actor::{
31 community_moderator_view::CommunityModeratorView,
32 community_person_ban_view::CommunityPersonBanView,
33 community_view::CommunityView,
37 email::{send_email, translations::Lang},
38 settings::structs::Settings,
39 utils::generate_random_string,
43 use rosetta_i18n::{Language, LanguageId};
46 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
48 F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
51 let pool = pool.clone();
52 let blocking_span = tracing::info_span!("blocking operation");
53 let res = actix_web::web::block(move || {
54 let entered = blocking_span.enter();
55 let conn = pool.get()?;
58 Ok(res) as Result<T, LemmyError>
65 #[tracing::instrument(skip_all)]
66 pub async fn is_mod_or_admin(
69 community_id: CommunityId,
70 ) -> Result<(), LemmyError> {
71 let is_mod_or_admin = blocking(pool, move |conn| {
72 CommunityView::is_mod_or_admin(conn, person_id, community_id)
76 return Err(LemmyError::from_message("not_a_mod_or_admin"));
81 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
82 if !local_user_view.person.admin {
83 return Err(LemmyError::from_message("not_an_admin"));
88 #[tracing::instrument(skip_all)]
89 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
90 blocking(pool, move |conn| Post::read(conn, post_id))
92 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))
95 #[tracing::instrument(skip_all)]
96 pub async fn mark_post_as_read(
100 ) -> Result<PostRead, LemmyError> {
101 let post_read_form = PostReadForm { post_id, person_id };
103 blocking(pool, move |conn| {
104 PostRead::mark_as_read(conn, &post_read_form)
107 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
110 #[tracing::instrument(skip_all)]
111 pub async fn mark_post_as_unread(
115 ) -> Result<usize, LemmyError> {
116 let post_read_form = PostReadForm { post_id, person_id };
118 blocking(pool, move |conn| {
119 PostRead::mark_as_unread(conn, &post_read_form)
122 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
125 #[tracing::instrument(skip_all)]
126 pub async fn get_local_user_view_from_jwt(
130 ) -> Result<LocalUserView, LemmyError> {
131 let claims = Claims::decode(jwt, &secret.jwt_secret)
132 .map_err(|e| e.with_message("not_logged_in"))?
134 let local_user_id = LocalUserId(claims.sub);
135 let local_user_view =
136 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
137 // Check for a site ban
138 if local_user_view.person.is_banned() {
139 return Err(LemmyError::from_message("site_ban"));
142 // Check for user deletion
143 if local_user_view.person.deleted {
144 return Err(LemmyError::from_message("deleted"));
147 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
152 /// Checks if user's token was issued before user's password reset.
153 pub fn check_validator_time(
154 validator_time: &chrono::NaiveDateTime,
156 ) -> Result<(), LemmyError> {
157 let user_validation_time = validator_time.timestamp();
158 if user_validation_time > claims.iat {
159 Err(LemmyError::from_message("not_logged_in"))
165 #[tracing::instrument(skip_all)]
166 pub async fn get_local_user_view_from_jwt_opt(
167 jwt: Option<&Sensitive<String>>,
170 ) -> Result<Option<LocalUserView>, LemmyError> {
172 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
177 #[tracing::instrument(skip_all)]
178 pub async fn get_local_user_settings_view_from_jwt(
179 jwt: &Sensitive<String>,
182 ) -> Result<LocalUserSettingsView, LemmyError> {
183 let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
184 .map_err(|e| e.with_message("not_logged_in"))?
186 let local_user_id = LocalUserId(claims.sub);
187 let local_user_view = blocking(pool, move |conn| {
188 LocalUserSettingsView::read(conn, local_user_id)
191 // Check for a site ban
192 if local_user_view.person.is_banned() {
193 return Err(LemmyError::from_message("site_ban"));
196 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
201 #[tracing::instrument(skip_all)]
202 pub async fn get_local_user_settings_view_from_jwt_opt(
203 jwt: Option<&Sensitive<String>>,
206 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
208 Some(jwt) => Ok(Some(
209 get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
215 #[tracing::instrument(skip_all)]
216 pub async fn check_community_ban(
218 community_id: CommunityId,
220 ) -> Result<(), LemmyError> {
222 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
223 if blocking(pool, is_banned).await? {
224 Err(LemmyError::from_message("community_ban"))
230 #[tracing::instrument(skip_all)]
231 pub async fn check_community_deleted_or_removed(
232 community_id: CommunityId,
234 ) -> Result<(), LemmyError> {
235 let community = blocking(pool, move |conn| Community::read(conn, community_id))
237 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
238 if community.deleted || community.removed {
239 Err(LemmyError::from_message("deleted"))
245 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
246 if post.deleted || post.removed {
247 Err(LemmyError::from_message("deleted"))
253 #[tracing::instrument(skip_all)]
254 pub async fn check_person_block(
256 potential_blocker_id: PersonId,
258 ) -> Result<(), LemmyError> {
259 let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
260 if blocking(pool, is_blocked).await? {
261 Err(LemmyError::from_message("person_block"))
267 #[tracing::instrument(skip_all)]
268 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
270 let site = blocking(pool, Site::read_local_site).await??;
271 if !site.enable_downvotes {
272 return Err(LemmyError::from_message("downvotes_disabled"));
278 #[tracing::instrument(skip_all)]
279 pub async fn check_private_instance(
280 local_user_view: &Option<LocalUserView>,
282 ) -> Result<(), LemmyError> {
283 if local_user_view.is_none() {
284 let site = blocking(pool, Site::read_local_site).await?;
286 // The site might not be set up yet
287 if let Ok(site) = site {
288 if site.private_instance {
289 return Err(LemmyError::from_message("instance_is_private"));
296 #[tracing::instrument(skip_all)]
297 pub async fn build_federated_instances(
300 ) -> Result<Option<FederatedInstances>, LemmyError> {
301 let federation_config = &settings.federation;
302 let hostname = &settings.hostname;
303 let federation = federation_config.to_owned();
304 if federation.enabled {
305 let distinct_communities = blocking(pool, move |conn| {
306 Community::distinct_federated_communities(conn)
310 let allowed = federation.allowed_instances;
311 let blocked = federation.blocked_instances;
313 let mut linked = distinct_communities
315 .map(|actor_id| Ok(actor_id.host_str().unwrap_or("").to_string()))
316 .collect::<Result<Vec<String>, LemmyError>>()?;
318 if let Some(allowed) = allowed.as_ref() {
319 linked.extend_from_slice(allowed);
322 if let Some(blocked) = blocked.as_ref() {
323 linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
326 // Sort and remove dupes
327 linked.sort_unstable();
330 Ok(Some(FederatedInstances {
340 /// Checks the password length
341 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
342 if !(10..=60).contains(&pass.len()) {
343 Err(LemmyError::from_message("invalid_password"))
349 /// Checks the site description length
350 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
351 if description.len() > 150 {
352 Err(LemmyError::from_message("site_description_length_overflow"))
358 /// Checks for a honeypot. If this field is filled, fail the rest of the function
359 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
360 if honeypot.is_some() {
361 Err(LemmyError::from_message("honeypot_fail"))
367 pub fn send_email_to_user(
368 local_user_view: &LocalUserView,
373 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
377 if let Some(user_email) = &local_user_view.local_user.email {
381 &local_user_view.person.name,
386 Err(e) => warn!("{}", e),
391 pub async fn send_password_reset_email(
392 user: &LocalUserView,
395 ) -> Result<(), LemmyError> {
396 // Generate a random token
397 let token = generate_random_string();
400 let token2 = token.clone();
401 let local_user_id = user.local_user.id;
402 blocking(pool, move |conn| {
403 PasswordResetRequest::create_token(conn, local_user_id, &token2)
407 let email = &user.local_user.email.to_owned().expect("email");
408 let lang = get_user_lang(user);
409 let subject = &lang.password_reset_subject(&user.person.name);
410 let protocol_and_hostname = settings.get_protocol_and_hostname();
411 let reset_link = format!("{}/password_change/{}", protocol_and_hostname, &token);
412 let body = &lang.password_reset_body(&user.person.name, reset_link);
413 send_email(subject, email, &user.person.name, body, settings)
416 /// Send a verification email
417 pub async fn send_verification_email(
418 user: &LocalUserView,
422 ) -> Result<(), LemmyError> {
423 let form = EmailVerificationForm {
424 local_user_id: user.local_user.id,
425 email: new_email.to_string(),
426 verification_token: generate_random_string(),
428 let verify_link = format!(
429 "{}/verify_email/{}",
430 settings.get_protocol_and_hostname(),
431 &form.verification_token
433 blocking(pool, move |conn| EmailVerification::create(conn, &form)).await??;
435 let lang = get_user_lang(user);
436 let subject = lang.verify_email_subject(&settings.hostname);
437 let body = lang.verify_email_body(&user.person.name, &settings.hostname, verify_link);
438 send_email(&subject, new_email, &user.person.name, &body, settings)?;
443 pub fn send_email_verification_success(
444 user: &LocalUserView,
446 ) -> Result<(), LemmyError> {
447 let email = &user.local_user.email.to_owned().expect("email");
448 let lang = get_user_lang(user);
449 let subject = &lang.email_verified_subject(&user.person.actor_id);
450 let body = &lang.email_verified_body();
451 send_email(subject, email, &user.person.name, body, settings)
454 pub fn get_user_lang(user: &LocalUserView) -> Lang {
455 let user_lang = LanguageId::new(user.local_user.lang.clone());
456 Lang::from_language_id(&user_lang).unwrap_or_else(|| {
457 let en = LanguageId::new("en");
458 Lang::from_language_id(&en).expect("default language")
462 pub fn send_application_approved_email(
463 user: &LocalUserView,
465 ) -> Result<(), LemmyError> {
466 let email = &user.local_user.email.to_owned().expect("email");
467 let lang = get_user_lang(user);
468 let subject = lang.registration_approved_subject(&user.person.actor_id);
469 let body = lang.registration_approved_body(&settings.hostname);
470 send_email(&subject, email, &user.person.name, &body, settings)
473 pub async fn check_registration_application(
475 local_user_view: &LocalUserView,
477 ) -> Result<(), LemmyError> {
478 if site.require_application
479 && !local_user_view.local_user.accepted_application
480 && !local_user_view.person.admin
482 // Fetch the registration, see if its denied
483 let local_user_id = local_user_view.local_user.id;
484 let registration = blocking(pool, move |conn| {
485 RegistrationApplication::find_by_local_user_id(conn, local_user_id)
488 if registration.deny_reason.is_some() {
489 return Err(LemmyError::from_message("registration_denied"));
491 return Err(LemmyError::from_message("registration_application_pending"));
497 /// TODO this check should be removed after https://github.com/LemmyNet/lemmy/issues/868 is done.
498 pub async fn check_private_instance_and_federation_enabled(
501 ) -> Result<(), LemmyError> {
502 let site_opt = blocking(pool, Site::read_local_site).await?;
504 if let Ok(site) = site_opt {
505 if site.private_instance && settings.federation.enabled {
506 return Err(LemmyError::from_message(
507 "Cannot have both private instance and federation enabled.",
514 pub async fn remove_user_data(banned_person_id: PersonId, pool: &DbPool) -> Result<(), LemmyError> {
516 blocking(pool, move |conn: &'_ _| {
517 Post::update_removed_for_creator(conn, banned_person_id, None, true)
522 // Remove all communities where they're the top mod
523 // for now, remove the communities manually
524 let first_mod_communities = blocking(pool, move |conn: &'_ _| {
525 CommunityModeratorView::get_community_first_mods(conn)
529 // Filter to only this banned users top communities
530 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
532 .filter(|fmc| fmc.moderator.id == banned_person_id)
535 for first_mod_community in banned_user_first_communities {
536 blocking(pool, move |conn: &'_ _| {
537 Community::update_removed(conn, first_mod_community.community.id, true)
543 blocking(pool, move |conn: &'_ _| {
544 Comment::update_removed_for_creator(conn, banned_person_id, true)
551 pub async fn remove_user_data_in_community(
552 community_id: CommunityId,
553 banned_person_id: PersonId,
555 ) -> Result<(), LemmyError> {
557 blocking(pool, move |conn| {
558 Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
563 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
564 let comments = blocking(pool, move |conn| {
565 CommentQueryBuilder::create(conn)
566 .creator_id(banned_person_id)
567 .community_id(community_id)
568 .limit(std::i64::MAX)
573 for comment_view in &comments {
574 let comment_id = comment_view.comment.id;
575 blocking(pool, move |conn| {
576 Comment::update_removed(conn, comment_id, true)
584 pub async fn delete_user_account(person_id: PersonId, pool: &DbPool) -> Result<(), LemmyError> {
586 let permadelete = move |conn: &'_ _| Comment::permadelete_for_creator(conn, person_id);
587 blocking(pool, permadelete)
589 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
592 let permadelete = move |conn: &'_ _| Post::permadelete_for_creator(conn, person_id);
593 blocking(pool, permadelete)
595 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
597 blocking(pool, move |conn| Person::delete_account(conn, person_id)).await??;
602 pub fn check_image_has_local_domain(url: &Option<DbUrl>) -> Result<(), LemmyError> {
603 if let Some(url) = url {
604 let settings = Settings::get();
605 let domain = url.domain().expect("url has domain");
606 if domain != settings.hostname {
607 return Err(LemmyError::from_message("image_not_local"));