8 use crate::site::FederatedInstances;
10 newtypes::{CommunityId, LocalUserId, PersonId, PostId},
14 email_verification::{EmailVerification, EmailVerificationForm},
15 password_reset_request::PasswordResetRequest,
16 person_block::PersonBlock,
17 post::{Post, PostRead, PostReadForm},
18 registration_application::RegistrationApplication,
22 traits::{Crud, Readable},
26 comment_view::CommentQueryBuilder,
27 local_user_view::{LocalUserSettingsView, LocalUserView},
29 use lemmy_db_views_actor::{
30 community_moderator_view::CommunityModeratorView,
31 community_person_ban_view::CommunityPersonBanView,
32 community_view::CommunityView,
37 settings::structs::{FederationConfig, Settings},
38 utils::generate_random_string,
44 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
46 F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
49 let pool = pool.clone();
50 let blocking_span = tracing::info_span!("blocking operation");
51 let res = actix_web::web::block(move || {
52 let entered = blocking_span.enter();
53 let conn = pool.get()?;
56 Ok(res) as Result<T, LemmyError>
63 #[tracing::instrument(skip_all)]
64 pub async fn is_mod_or_admin(
67 community_id: CommunityId,
68 ) -> Result<(), LemmyError> {
69 let is_mod_or_admin = blocking(pool, move |conn| {
70 CommunityView::is_mod_or_admin(conn, person_id, community_id)
74 return Err(LemmyError::from_message("not_a_mod_or_admin"));
79 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
80 if !local_user_view.person.admin {
81 return Err(LemmyError::from_message("not_an_admin"));
86 #[tracing::instrument(skip_all)]
87 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
88 blocking(pool, move |conn| Post::read(conn, post_id))
90 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))
93 #[tracing::instrument(skip_all)]
94 pub async fn mark_post_as_read(
98 ) -> Result<PostRead, LemmyError> {
99 let post_read_form = PostReadForm { post_id, person_id };
101 blocking(pool, move |conn| {
102 PostRead::mark_as_read(conn, &post_read_form)
105 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
108 #[tracing::instrument(skip_all)]
109 pub async fn mark_post_as_unread(
113 ) -> Result<usize, LemmyError> {
114 let post_read_form = PostReadForm { post_id, person_id };
116 blocking(pool, move |conn| {
117 PostRead::mark_as_unread(conn, &post_read_form)
120 .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
123 #[tracing::instrument(skip_all)]
124 pub async fn get_local_user_view_from_jwt(
128 ) -> Result<LocalUserView, LemmyError> {
129 let claims = Claims::decode(jwt, &secret.jwt_secret)
130 .map_err(|e| e.with_message("not_logged_in"))?
132 let local_user_id = LocalUserId(claims.sub);
133 let local_user_view =
134 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
135 // Check for a site ban
136 if local_user_view.person.is_banned() {
137 return Err(LemmyError::from_message("site_ban"));
140 // Check for user deletion
141 if local_user_view.person.deleted {
142 return Err(LemmyError::from_message("deleted"));
145 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
150 /// Checks if user's token was issued before user's password reset.
151 pub fn check_validator_time(
152 validator_time: &chrono::NaiveDateTime,
154 ) -> Result<(), LemmyError> {
155 let user_validation_time = validator_time.timestamp();
156 if user_validation_time > claims.iat {
157 Err(LemmyError::from_message("not_logged_in"))
163 #[tracing::instrument(skip_all)]
164 pub async fn get_local_user_view_from_jwt_opt(
165 jwt: Option<&Sensitive<String>>,
168 ) -> Result<Option<LocalUserView>, LemmyError> {
170 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
175 #[tracing::instrument(skip_all)]
176 pub async fn get_local_user_settings_view_from_jwt(
177 jwt: &Sensitive<String>,
180 ) -> Result<LocalUserSettingsView, LemmyError> {
181 let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
182 .map_err(|e| e.with_message("not_logged_in"))?
184 let local_user_id = LocalUserId(claims.sub);
185 let local_user_view = blocking(pool, move |conn| {
186 LocalUserSettingsView::read(conn, local_user_id)
189 // Check for a site ban
190 if local_user_view.person.is_banned() {
191 return Err(LemmyError::from_message("site_ban"));
194 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
199 #[tracing::instrument(skip_all)]
200 pub async fn get_local_user_settings_view_from_jwt_opt(
201 jwt: Option<&Sensitive<String>>,
204 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
206 Some(jwt) => Ok(Some(
207 get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
213 #[tracing::instrument(skip_all)]
214 pub async fn check_community_ban(
216 community_id: CommunityId,
218 ) -> Result<(), LemmyError> {
220 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
221 if blocking(pool, is_banned).await? {
222 Err(LemmyError::from_message("community_ban"))
228 #[tracing::instrument(skip_all)]
229 pub async fn check_community_deleted_or_removed(
230 community_id: CommunityId,
232 ) -> Result<(), LemmyError> {
233 let community = blocking(pool, move |conn| Community::read(conn, community_id))
235 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
236 if community.deleted || community.removed {
237 Err(LemmyError::from_message("deleted"))
243 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
244 if post.deleted || post.removed {
245 Err(LemmyError::from_message("deleted"))
251 #[tracing::instrument(skip_all)]
252 pub async fn check_person_block(
254 potential_blocker_id: PersonId,
256 ) -> Result<(), LemmyError> {
257 let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
258 if blocking(pool, is_blocked).await? {
259 Err(LemmyError::from_message("person_block"))
265 #[tracing::instrument(skip_all)]
266 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
268 let site = blocking(pool, Site::read_local_site).await??;
269 if !site.enable_downvotes {
270 return Err(LemmyError::from_message("downvotes_disabled"));
276 #[tracing::instrument(skip_all)]
277 pub async fn check_private_instance(
278 local_user_view: &Option<LocalUserView>,
280 ) -> Result<(), LemmyError> {
281 if local_user_view.is_none() {
282 let site = blocking(pool, Site::read_local_site).await?;
284 // The site might not be set up yet
285 if let Ok(site) = site {
286 if site.private_instance {
287 return Err(LemmyError::from_message("instance_is_private"));
294 #[tracing::instrument(skip_all)]
295 pub async fn build_federated_instances(
297 federation_config: &FederationConfig,
299 ) -> Result<Option<FederatedInstances>, LemmyError> {
300 let federation = federation_config.to_owned();
301 if federation.enabled {
302 let distinct_communities = blocking(pool, move |conn| {
303 Community::distinct_federated_communities(conn)
307 let allowed = federation.allowed_instances;
308 let blocked = federation.blocked_instances;
310 let mut linked = distinct_communities
312 .map(|actor_id| Ok(actor_id.host_str().unwrap_or("").to_string()))
313 .collect::<Result<Vec<String>, LemmyError>>()?;
315 if let Some(allowed) = allowed.as_ref() {
316 linked.extend_from_slice(allowed);
319 if let Some(blocked) = blocked.as_ref() {
320 linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
323 // Sort and remove dupes
324 linked.sort_unstable();
327 Ok(Some(FederatedInstances {
337 /// Checks the password length
338 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
339 if !(10..=60).contains(&pass.len()) {
340 Err(LemmyError::from_message("invalid_password"))
346 /// Checks the site description length
347 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
348 if description.len() > 150 {
349 Err(LemmyError::from_message("site_description_length_overflow"))
355 /// Checks for a honeypot. If this field is filled, fail the rest of the function
356 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
357 if honeypot.is_some() {
358 Err(LemmyError::from_message("honeypot_fail"))
364 pub fn send_email_to_user(
365 local_user_view: &LocalUserView,
368 comment_content: &str,
371 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
375 if let Some(user_email) = &local_user_view.local_user.email {
376 let subject = &format!(
378 subject_text, settings.hostname, local_user_view.person.name,
381 "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
383 local_user_view.person.name,
385 settings.get_protocol_and_hostname()
390 &local_user_view.person.name,
395 Err(e) => tracing::error!("{}", e),
400 pub async fn send_password_reset_email(
401 local_user_view: &LocalUserView,
404 ) -> Result<(), LemmyError> {
405 // Generate a random token
406 let token = generate_random_string();
409 let token2 = token.clone();
410 let local_user_id = local_user_view.local_user.id;
411 blocking(pool, move |conn| {
412 PasswordResetRequest::create_token(conn, local_user_id, &token2)
416 let email = &local_user_view.local_user.email.to_owned().expect("email");
417 let subject = &format!("Password reset for {}", local_user_view.person.name);
418 let protocol_and_hostname = settings.get_protocol_and_hostname();
419 let html = &format!("<h1>Password Reset Request for {}</h1><br><a href={}/password_change/{}>Click here to reset your password</a>", local_user_view.person.name, protocol_and_hostname, &token);
420 send_email(subject, email, &local_user_view.person.name, html, settings)
423 /// Send a verification email
424 pub async fn send_verification_email(
425 local_user_id: LocalUserId,
430 ) -> Result<(), LemmyError> {
431 let form = EmailVerificationForm {
433 email: new_email.to_string(),
434 verification_token: generate_random_string(),
436 let verify_link = format!(
437 "{}/verify_email/{}",
438 settings.get_protocol_and_hostname(),
439 &form.verification_token
441 blocking(pool, move |conn| EmailVerification::create(conn, &form)).await??;
443 let subject = format!("Verify your email address for {}", settings.hostname);
446 "Please click the link below to verify your email address ",
447 "for the account @{}@{}. Ignore this email if the account isn't yours.<br><br>",
448 "<a href=\"{}\">Verify your email</a>"
450 username, settings.hostname, verify_link
452 send_email(&subject, new_email, username, &body, settings)?;
457 pub fn send_email_verification_success(
458 local_user_view: &LocalUserView,
460 ) -> Result<(), LemmyError> {
461 let email = &local_user_view.local_user.email.to_owned().expect("email");
462 let subject = &format!("Email verified for {}", local_user_view.person.actor_id);
463 let html = "Your email has been verified.";
464 send_email(subject, email, &local_user_view.person.name, html, settings)
467 pub fn send_application_approved_email(
468 local_user_view: &LocalUserView,
470 ) -> Result<(), LemmyError> {
471 let email = &local_user_view.local_user.email.to_owned().expect("email");
472 let subject = &format!(
473 "Registration approved for {}",
474 local_user_view.person.actor_id
477 "Your registration application has been approved. Welcome to {}!",
480 send_email(subject, email, &local_user_view.person.name, html, settings)
483 pub async fn check_registration_application(
485 local_user_view: &LocalUserView,
487 ) -> Result<(), LemmyError> {
488 if site.require_application
489 && !local_user_view.local_user.accepted_application
490 && !local_user_view.person.admin
492 // Fetch the registration, see if its denied
493 let local_user_id = local_user_view.local_user.id;
494 let registration = blocking(pool, move |conn| {
495 RegistrationApplication::find_by_local_user_id(conn, local_user_id)
498 if registration.deny_reason.is_some() {
499 return Err(LemmyError::from_message("registration_denied"));
501 return Err(LemmyError::from_message("registration_application_pending"));
507 /// TODO this check should be removed after https://github.com/LemmyNet/lemmy/issues/868 is done.
508 pub async fn check_private_instance_and_federation_enabled(
511 ) -> Result<(), LemmyError> {
512 let site_opt = blocking(pool, Site::read_local_site).await?;
514 if let Ok(site) = site_opt {
515 if site.private_instance && settings.federation.enabled {
516 return Err(LemmyError::from_message(
517 "Cannot have both private instance and federation enabled.",
524 pub async fn remove_user_data(banned_person_id: PersonId, pool: &DbPool) -> Result<(), LemmyError> {
526 blocking(pool, move |conn: &'_ _| {
527 Post::update_removed_for_creator(conn, banned_person_id, None, true)
532 // Remove all communities where they're the top mod
533 // for now, remove the communities manually
534 let first_mod_communities = blocking(pool, move |conn: &'_ _| {
535 CommunityModeratorView::get_community_first_mods(conn)
539 // Filter to only this banned users top communities
540 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
542 .filter(|fmc| fmc.moderator.id == banned_person_id)
545 for first_mod_community in banned_user_first_communities {
546 blocking(pool, move |conn: &'_ _| {
547 Community::update_removed(conn, first_mod_community.community.id, true)
553 blocking(pool, move |conn: &'_ _| {
554 Comment::update_removed_for_creator(conn, banned_person_id, true)
561 pub async fn remove_user_data_in_community(
562 community_id: CommunityId,
563 banned_person_id: PersonId,
565 ) -> Result<(), LemmyError> {
567 blocking(pool, move |conn| {
568 Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
573 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
574 let comments = blocking(pool, move |conn| {
575 CommentQueryBuilder::create(conn)
576 .creator_id(banned_person_id)
577 .community_id(community_id)
578 .limit(std::i64::MAX)
583 for comment_view in &comments {
584 let comment_id = comment_view.comment.id;
585 blocking(pool, move |conn| {
586 Comment::update_removed(conn, comment_id, true)
594 pub fn check_image_has_local_domain(url: &Option<String>) -> Result<(), LemmyError> {
595 if let Some(url) = url {
596 let settings = Settings::get();
597 let url = Url::parse(url)?;
598 let domain = url.domain().expect("url has domain");
599 if domain != settings.hostname {
600 return Err(LemmyError::from_message("image_not_local"));