1 use crate::{sensitive::Sensitive, site::FederatedInstances};
3 newtypes::{CommunityId, LocalUserId, PersonId, PostId},
7 email_verification::{EmailVerification, EmailVerificationForm},
8 password_reset_request::PasswordResetRequest,
10 person_block::PersonBlock,
11 post::{Post, PostRead, PostReadForm},
12 registration_application::RegistrationApplication,
16 traits::{Crud, Readable},
20 comment_view::CommentQueryBuilder,
21 structs::{LocalUserSettingsView, LocalUserView},
23 use lemmy_db_views_actor::structs::{
24 CommunityModeratorView,
25 CommunityPersonBanView,
30 email::{send_email, translations::Lang},
31 settings::structs::Settings,
32 utils::generate_random_string,
35 use rosetta_i18n::{Language, LanguageId};
38 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
40 F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
43 let pool = pool.clone();
44 let blocking_span = tracing::info_span!("blocking operation");
45 let res = actix_web::web::block(move || {
46 let entered = blocking_span.enter();
47 let conn = pool.get()?;
50 Ok(res) as Result<T, LemmyError>
57 #[tracing::instrument(skip_all)]
58 pub async fn is_mod_or_admin(
61 community_id: CommunityId,
62 ) -> Result<(), LemmyError> {
63 let is_mod_or_admin = blocking(pool, move |conn| {
64 CommunityView::is_mod_or_admin(conn, person_id, community_id)
68 return Err(LemmyError::from_message("not_a_mod_or_admin"));
73 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
74 if !local_user_view.person.admin {
75 return Err(LemmyError::from_message("not_an_admin"));
80 #[tracing::instrument(skip_all)]
81 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
82 blocking(pool, move |conn| Post::read(conn, post_id))
84 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))
87 #[tracing::instrument(skip_all)]
88 pub async fn mark_post_as_read(
92 ) -> Result<PostRead, LemmyError> {
93 let post_read_form = PostReadForm { post_id, person_id };
95 blocking(pool, move |conn| {
96 PostRead::mark_as_read(conn, &post_read_form)
99 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
102 #[tracing::instrument(skip_all)]
103 pub async fn mark_post_as_unread(
107 ) -> Result<usize, LemmyError> {
108 let post_read_form = PostReadForm { post_id, person_id };
110 blocking(pool, move |conn| {
111 PostRead::mark_as_unread(conn, &post_read_form)
114 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
117 #[tracing::instrument(skip_all)]
118 pub async fn get_local_user_view_from_jwt(
122 ) -> Result<LocalUserView, LemmyError> {
123 let claims = Claims::decode(jwt, &secret.jwt_secret)
124 .map_err(|e| e.with_message("not_logged_in"))?
126 let local_user_id = LocalUserId(claims.sub);
127 let local_user_view =
128 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
129 // Check for a site ban
130 if local_user_view.person.is_banned() {
131 return Err(LemmyError::from_message("site_ban"));
134 // Check for user deletion
135 if local_user_view.person.deleted {
136 return Err(LemmyError::from_message("deleted"));
139 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
144 /// Checks if user's token was issued before user's password reset.
145 pub fn check_validator_time(
146 validator_time: &chrono::NaiveDateTime,
148 ) -> Result<(), LemmyError> {
149 let user_validation_time = validator_time.timestamp();
150 if user_validation_time > claims.iat {
151 Err(LemmyError::from_message("not_logged_in"))
157 #[tracing::instrument(skip_all)]
158 pub async fn get_local_user_view_from_jwt_opt(
159 jwt: Option<&Sensitive<String>>,
162 ) -> Result<Option<LocalUserView>, LemmyError> {
164 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
169 #[tracing::instrument(skip_all)]
170 pub async fn get_local_user_settings_view_from_jwt(
171 jwt: &Sensitive<String>,
174 ) -> Result<LocalUserSettingsView, LemmyError> {
175 let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
176 .map_err(|e| e.with_message("not_logged_in"))?
178 let local_user_id = LocalUserId(claims.sub);
179 let local_user_view = blocking(pool, move |conn| {
180 LocalUserSettingsView::read(conn, local_user_id)
183 // Check for a site ban
184 if local_user_view.person.is_banned() {
185 return Err(LemmyError::from_message("site_ban"));
188 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
193 #[tracing::instrument(skip_all)]
194 pub async fn get_local_user_settings_view_from_jwt_opt(
195 jwt: Option<&Sensitive<String>>,
198 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
200 Some(jwt) => Ok(Some(
201 get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
207 #[tracing::instrument(skip_all)]
208 pub async fn check_community_ban(
210 community_id: CommunityId,
212 ) -> Result<(), LemmyError> {
214 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
215 if blocking(pool, is_banned).await? {
216 Err(LemmyError::from_message("community_ban"))
222 #[tracing::instrument(skip_all)]
223 pub async fn check_community_deleted_or_removed(
224 community_id: CommunityId,
226 ) -> Result<(), LemmyError> {
227 let community = blocking(pool, move |conn| Community::read(conn, community_id))
229 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
230 if community.deleted || community.removed {
231 Err(LemmyError::from_message("deleted"))
237 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
238 if post.deleted || post.removed {
239 Err(LemmyError::from_message("deleted"))
245 #[tracing::instrument(skip_all)]
246 pub async fn check_person_block(
248 potential_blocker_id: PersonId,
250 ) -> Result<(), LemmyError> {
251 let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
252 if blocking(pool, is_blocked).await? {
253 Err(LemmyError::from_message("person_block"))
259 #[tracing::instrument(skip_all)]
260 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
262 let site = blocking(pool, Site::read_local_site).await??;
263 if !site.enable_downvotes {
264 return Err(LemmyError::from_message("downvotes_disabled"));
270 #[tracing::instrument(skip_all)]
271 pub async fn check_private_instance(
272 local_user_view: &Option<LocalUserView>,
274 ) -> Result<(), LemmyError> {
275 if local_user_view.is_none() {
276 let site = blocking(pool, Site::read_local_site).await?;
278 // The site might not be set up yet
279 if let Ok(site) = site {
280 if site.private_instance {
281 return Err(LemmyError::from_message("instance_is_private"));
288 #[tracing::instrument(skip_all)]
289 pub async fn build_federated_instances(
292 ) -> Result<Option<FederatedInstances>, LemmyError> {
293 let federation_config = &settings.federation;
294 let hostname = &settings.hostname;
295 let federation = federation_config.to_owned();
296 if federation.enabled {
297 let distinct_communities = blocking(pool, move |conn| {
298 Community::distinct_federated_communities(conn)
302 let allowed = federation.allowed_instances;
303 let blocked = federation.blocked_instances;
305 let mut linked = distinct_communities
307 .map(|actor_id| Ok(actor_id.host_str().unwrap_or("").to_string()))
308 .collect::<Result<Vec<String>, LemmyError>>()?;
310 if let Some(allowed) = allowed.as_ref() {
311 linked.extend_from_slice(allowed);
314 if let Some(blocked) = blocked.as_ref() {
315 linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
318 // Sort and remove dupes
319 linked.sort_unstable();
322 Ok(Some(FederatedInstances {
332 /// Checks the password length
333 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
334 if !(10..=60).contains(&pass.len()) {
335 Err(LemmyError::from_message("invalid_password"))
341 /// Checks the site description length
342 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
343 if description.len() > 150 {
344 Err(LemmyError::from_message("site_description_length_overflow"))
350 /// Checks for a honeypot. If this field is filled, fail the rest of the function
351 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
352 if honeypot.is_some() {
353 Err(LemmyError::from_message("honeypot_fail"))
359 pub fn send_email_to_user(
360 local_user_view: &LocalUserView,
365 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
369 if let Some(user_email) = &local_user_view.local_user.email {
373 &local_user_view.person.name,
378 Err(e) => warn!("{}", e),
383 pub async fn send_password_reset_email(
384 user: &LocalUserView,
387 ) -> Result<(), LemmyError> {
388 // Generate a random token
389 let token = generate_random_string();
392 let token2 = token.clone();
393 let local_user_id = user.local_user.id;
394 blocking(pool, move |conn| {
395 PasswordResetRequest::create_token(conn, local_user_id, &token2)
399 let email = &user.local_user.email.to_owned().expect("email");
400 let lang = get_user_lang(user);
401 let subject = &lang.password_reset_subject(&user.person.name);
402 let protocol_and_hostname = settings.get_protocol_and_hostname();
403 let reset_link = format!("{}/password_change/{}", protocol_and_hostname, &token);
404 let body = &lang.password_reset_body(reset_link, &user.person.name);
405 send_email(subject, email, &user.person.name, body, settings)
408 /// Send a verification email
409 pub async fn send_verification_email(
410 user: &LocalUserView,
414 ) -> Result<(), LemmyError> {
415 let form = EmailVerificationForm {
416 local_user_id: user.local_user.id,
417 email: new_email.to_string(),
418 verification_token: generate_random_string(),
420 let verify_link = format!(
421 "{}/verify_email/{}",
422 settings.get_protocol_and_hostname(),
423 &form.verification_token
425 blocking(pool, move |conn| EmailVerification::create(conn, &form)).await??;
427 let lang = get_user_lang(user);
428 let subject = lang.verify_email_subject(&settings.hostname);
429 let body = lang.verify_email_body(&settings.hostname, &user.person.name, verify_link);
430 send_email(&subject, new_email, &user.person.name, &body, settings)?;
435 pub fn send_email_verification_success(
436 user: &LocalUserView,
438 ) -> Result<(), LemmyError> {
439 let email = &user.local_user.email.to_owned().expect("email");
440 let lang = get_user_lang(user);
441 let subject = &lang.email_verified_subject(&user.person.actor_id);
442 let body = &lang.email_verified_body();
443 send_email(subject, email, &user.person.name, body, settings)
446 pub fn get_user_lang(user: &LocalUserView) -> Lang {
447 let user_lang = LanguageId::new(user.local_user.lang.clone());
448 Lang::from_language_id(&user_lang).unwrap_or_else(|| {
449 let en = LanguageId::new("en");
450 Lang::from_language_id(&en).expect("default language")
454 pub fn send_application_approved_email(
455 user: &LocalUserView,
457 ) -> Result<(), LemmyError> {
458 let email = &user.local_user.email.to_owned().expect("email");
459 let lang = get_user_lang(user);
460 let subject = lang.registration_approved_subject(&user.person.actor_id);
461 let body = lang.registration_approved_body(&settings.hostname);
462 send_email(&subject, email, &user.person.name, &body, settings)
465 pub async fn check_registration_application(
467 local_user_view: &LocalUserView,
469 ) -> Result<(), LemmyError> {
470 if site.require_application
471 && !local_user_view.local_user.accepted_application
472 && !local_user_view.person.admin
474 // Fetch the registration, see if its denied
475 let local_user_id = local_user_view.local_user.id;
476 let registration = blocking(pool, move |conn| {
477 RegistrationApplication::find_by_local_user_id(conn, local_user_id)
480 if let Some(deny_reason) = registration.deny_reason {
481 let lang = get_user_lang(local_user_view);
482 let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason);
483 return Err(LemmyError::from_message(®istration_denied_message));
485 return Err(LemmyError::from_message("registration_application_pending"));
491 /// TODO this check should be removed after https://github.com/LemmyNet/lemmy/issues/868 is done.
492 pub async fn check_private_instance_and_federation_enabled(
495 ) -> Result<(), LemmyError> {
496 let site_opt = blocking(pool, Site::read_local_site).await?;
498 if let Ok(site) = site_opt {
499 if site.private_instance && settings.federation.enabled {
500 return Err(LemmyError::from_message(
501 "Cannot have both private instance and federation enabled.",
508 pub async fn remove_user_data(banned_person_id: PersonId, pool: &DbPool) -> Result<(), LemmyError> {
510 blocking(pool, move |conn: &'_ _| {
511 Post::update_removed_for_creator(conn, banned_person_id, None, true)
516 // Remove all communities where they're the top mod
517 // for now, remove the communities manually
518 let first_mod_communities = blocking(pool, move |conn: &'_ _| {
519 CommunityModeratorView::get_community_first_mods(conn)
523 // Filter to only this banned users top communities
524 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
526 .filter(|fmc| fmc.moderator.id == banned_person_id)
529 for first_mod_community in banned_user_first_communities {
530 blocking(pool, move |conn: &'_ _| {
531 Community::update_removed(conn, first_mod_community.community.id, true)
537 blocking(pool, move |conn: &'_ _| {
538 Comment::update_removed_for_creator(conn, banned_person_id, true)
545 pub async fn remove_user_data_in_community(
546 community_id: CommunityId,
547 banned_person_id: PersonId,
549 ) -> Result<(), LemmyError> {
551 blocking(pool, move |conn| {
552 Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
557 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
558 let comments = blocking(pool, move |conn| {
559 CommentQueryBuilder::create(conn)
560 .creator_id(banned_person_id)
561 .community_id(community_id)
562 .limit(std::i64::MAX)
567 for comment_view in &comments {
568 let comment_id = comment_view.comment.id;
569 blocking(pool, move |conn| {
570 Comment::update_removed(conn, comment_id, true)
578 pub async fn delete_user_account(person_id: PersonId, pool: &DbPool) -> Result<(), LemmyError> {
580 let permadelete = move |conn: &'_ _| Comment::permadelete_for_creator(conn, person_id);
581 blocking(pool, permadelete)
583 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
586 let permadelete = move |conn: &'_ _| Post::permadelete_for_creator(conn, person_id);
587 blocking(pool, permadelete)
589 .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
591 blocking(pool, move |conn| Person::delete_account(conn, person_id)).await??;