8 use crate::site::FederatedInstances;
9 use itertools::Itertools;
10 use lemmy_db_schema::{
11 newtypes::{CommunityId, LocalUserId, PersonId, PostId},
15 email_verification::{EmailVerification, EmailVerificationForm},
16 password_reset_request::PasswordResetRequest,
17 person_block::PersonBlock,
18 post::{Post, PostRead, PostReadForm},
19 registration_application::RegistrationApplication,
23 traits::{ApubActor, 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,
38 settings::structs::{FederationConfig, Settings},
39 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(LemmyError::from)
91 .map_err(|e| e.with_message("couldnt_find_post"))
94 #[tracing::instrument(skip_all)]
95 pub async fn mark_post_as_read(
99 ) -> Result<PostRead, LemmyError> {
100 let post_read_form = PostReadForm { post_id, person_id };
102 blocking(pool, move |conn| {
103 PostRead::mark_as_read(conn, &post_read_form)
106 .map_err(LemmyError::from)
107 .map_err(|e| e.with_message("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(LemmyError::from)
123 .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
126 #[tracing::instrument(skip_all)]
127 pub async fn get_local_user_view_from_jwt(
131 ) -> Result<LocalUserView, LemmyError> {
132 let claims = Claims::decode(jwt, &secret.jwt_secret)
133 .map_err(LemmyError::from)
134 .map_err(|e| e.with_message("not_logged_in"))?
136 let local_user_id = LocalUserId(claims.sub);
137 let local_user_view =
138 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
139 // Check for a site ban
140 if local_user_view.person.is_banned() {
141 return Err(LemmyError::from_message("site_ban"));
144 // Check for user deletion
145 if local_user_view.person.deleted {
146 return Err(LemmyError::from_message("deleted"));
149 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
154 /// Checks if user's token was issued before user's password reset.
155 pub fn check_validator_time(
156 validator_time: &chrono::NaiveDateTime,
158 ) -> Result<(), LemmyError> {
159 let user_validation_time = validator_time.timestamp();
160 if user_validation_time > claims.iat {
161 Err(LemmyError::from_message("not_logged_in"))
167 #[tracing::instrument(skip_all)]
168 pub async fn get_local_user_view_from_jwt_opt(
169 jwt: Option<&Sensitive<String>>,
172 ) -> Result<Option<LocalUserView>, LemmyError> {
174 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
179 #[tracing::instrument(skip_all)]
180 pub async fn get_local_user_settings_view_from_jwt(
181 jwt: &Sensitive<String>,
184 ) -> Result<LocalUserSettingsView, LemmyError> {
185 let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
186 .map_err(LemmyError::from)
187 .map_err(|e| e.with_message("not_logged_in"))?
189 let local_user_id = LocalUserId(claims.sub);
190 let local_user_view = blocking(pool, move |conn| {
191 LocalUserSettingsView::read(conn, local_user_id)
194 // Check for a site ban
195 if local_user_view.person.is_banned() {
196 return Err(LemmyError::from_message("site_ban"));
199 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
204 #[tracing::instrument(skip_all)]
205 pub async fn get_local_user_settings_view_from_jwt_opt(
206 jwt: Option<&Sensitive<String>>,
209 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
211 Some(jwt) => Ok(Some(
212 get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
218 #[tracing::instrument(skip_all)]
219 pub async fn check_community_ban(
221 community_id: CommunityId,
223 ) -> Result<(), LemmyError> {
225 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
226 if blocking(pool, is_banned).await? {
227 Err(LemmyError::from_message("community_ban"))
233 #[tracing::instrument(skip_all)]
234 pub async fn check_community_deleted_or_removed(
235 community_id: CommunityId,
237 ) -> Result<(), LemmyError> {
238 let community = blocking(pool, move |conn| Community::read(conn, community_id))
240 .map_err(LemmyError::from)
241 .map_err(|e| e.with_message("couldnt_find_community"))?;
242 if community.deleted || community.removed {
243 Err(LemmyError::from_message("deleted"))
249 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
250 if post.deleted || post.removed {
251 Err(LemmyError::from_message("deleted"))
257 #[tracing::instrument(skip_all)]
258 pub async fn check_person_block(
260 potential_blocker_id: PersonId,
262 ) -> Result<(), LemmyError> {
263 let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
264 if blocking(pool, is_blocked).await? {
265 Err(LemmyError::from_message("person_block"))
271 #[tracing::instrument(skip_all)]
272 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
274 let site = blocking(pool, Site::read_local_site).await??;
275 if !site.enable_downvotes {
276 return Err(LemmyError::from_message("downvotes_disabled"));
282 #[tracing::instrument(skip_all)]
283 pub async fn check_private_instance(
284 local_user_view: &Option<LocalUserView>,
286 ) -> Result<(), LemmyError> {
287 if local_user_view.is_none() {
288 let site = blocking(pool, Site::read_local_site).await?;
290 // The site might not be set up yet
291 if let Ok(site) = site {
292 if site.private_instance {
293 return Err(LemmyError::from_message("instance_is_private"));
300 #[tracing::instrument(skip_all)]
301 pub async fn build_federated_instances(
303 federation_config: &FederationConfig,
305 ) -> Result<Option<FederatedInstances>, LemmyError> {
306 let federation = federation_config.to_owned();
307 if federation.enabled {
308 let distinct_communities = blocking(pool, move |conn| {
309 Community::distinct_federated_communities(conn)
313 let allowed = federation.allowed_instances;
314 let blocked = federation.blocked_instances;
316 let mut linked = distinct_communities
318 .map(|actor_id| Ok(actor_id.host_str().unwrap_or("").to_string()))
319 .collect::<Result<Vec<String>, LemmyError>>()?;
321 if let Some(allowed) = allowed.as_ref() {
322 linked.extend_from_slice(allowed);
325 if let Some(blocked) = blocked.as_ref() {
326 linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
329 // Sort and remove dupes
330 linked.sort_unstable();
333 Ok(Some(FederatedInstances {
343 /// Checks the password length
344 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
345 if !(10..=60).contains(&pass.len()) {
346 Err(LemmyError::from_message("invalid_password"))
352 /// Checks the site description length
353 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
354 if description.len() > 150 {
355 Err(LemmyError::from_message("site_description_length_overflow"))
361 /// Checks for a honeypot. If this field is filled, fail the rest of the function
362 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
363 if honeypot.is_some() {
364 Err(LemmyError::from_message("honeypot_fail"))
370 pub fn send_email_to_user(
371 local_user_view: &LocalUserView,
374 comment_content: &str,
377 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
381 if let Some(user_email) = &local_user_view.local_user.email {
382 let subject = &format!(
384 subject_text, settings.hostname, local_user_view.person.name,
387 "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
389 local_user_view.person.name,
391 settings.get_protocol_and_hostname()
396 &local_user_view.person.name,
401 Err(e) => tracing::error!("{}", e),
406 pub async fn send_password_reset_email(
407 local_user_view: &LocalUserView,
410 ) -> Result<(), LemmyError> {
411 // Generate a random token
412 let token = generate_random_string();
415 let token2 = token.clone();
416 let local_user_id = local_user_view.local_user.id;
417 blocking(pool, move |conn| {
418 PasswordResetRequest::create_token(conn, local_user_id, &token2)
422 let email = &local_user_view.local_user.email.to_owned().expect("email");
423 let subject = &format!("Password reset for {}", local_user_view.person.name);
424 let protocol_and_hostname = settings.get_protocol_and_hostname();
425 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);
426 send_email(subject, email, &local_user_view.person.name, html, settings)
429 /// Send a verification email
430 pub async fn send_verification_email(
431 local_user_id: LocalUserId,
436 ) -> Result<(), LemmyError> {
437 let form = EmailVerificationForm {
439 email: new_email.to_string(),
440 verification_token: generate_random_string(),
442 let verify_link = format!(
443 "{}/verify_email/{}",
444 settings.get_protocol_and_hostname(),
445 &form.verification_token
447 blocking(pool, move |conn| EmailVerification::create(conn, &form)).await??;
449 let subject = format!("Verify your email address for {}", settings.hostname);
452 "Please click the link below to verify your email address ",
453 "for the account @{}@{}. Ignore this email if the account isn't yours.<br><br>",
454 "<a href=\"{}\">Verify your email</a>"
456 username, settings.hostname, verify_link
458 send_email(&subject, new_email, username, &body, settings)?;
463 pub fn send_email_verification_success(
464 local_user_view: &LocalUserView,
466 ) -> Result<(), LemmyError> {
467 let email = &local_user_view.local_user.email.to_owned().expect("email");
468 let subject = &format!("Email verified for {}", local_user_view.person.actor_id);
469 let html = "Your email has been verified.";
470 send_email(subject, email, &local_user_view.person.name, html, settings)
473 pub fn send_application_approved_email(
474 local_user_view: &LocalUserView,
476 ) -> Result<(), LemmyError> {
477 let email = &local_user_view.local_user.email.to_owned().expect("email");
478 let subject = &format!(
479 "Registration approved for {}",
480 local_user_view.person.actor_id
483 "Your registration application has been approved. Welcome to {}!",
486 send_email(subject, email, &local_user_view.person.name, html, settings)
489 pub async fn check_registration_application(
491 local_user_view: &LocalUserView,
493 ) -> Result<(), LemmyError> {
494 if site.require_application
495 && !local_user_view.local_user.accepted_application
496 && !local_user_view.person.admin
498 // Fetch the registration, see if its denied
499 let local_user_id = local_user_view.local_user.id;
500 let registration = blocking(pool, move |conn| {
501 RegistrationApplication::find_by_local_user_id(conn, local_user_id)
504 if registration.deny_reason.is_some() {
505 return Err(LemmyError::from_message("registration_denied"));
507 return Err(LemmyError::from_message("registration_application_pending"));
513 /// TODO this check should be removed after https://github.com/LemmyNet/lemmy/issues/868 is done.
514 pub async fn check_private_instance_and_federation_enabled(
517 ) -> Result<(), LemmyError> {
518 let site_opt = blocking(pool, Site::read_local_site).await?;
520 if let Ok(site) = site_opt {
521 if site.private_instance && settings.federation.enabled {
522 return Err(LemmyError::from_message(
523 "Cannot have both private instance and federation enabled.",
530 /// Resolve actor identifier (eg `!news@example.com`) from local database to avoid network requests.
531 /// This only works for local actors, and remote actors which were previously fetched (so it doesnt
532 /// trigger any new fetch).
533 #[tracing::instrument(skip_all)]
534 pub async fn resolve_actor_identifier<Actor>(
537 ) -> Result<Actor, LemmyError>
539 Actor: ApubActor + Send + 'static,
542 if identifier.contains('@') {
543 let (name, domain) = identifier
546 .expect("invalid query");
547 let name = name.to_string();
548 let domain = format!("{}://{}", Settings::get().get_protocol_string(), domain);
550 blocking(pool, move |conn| {
551 Actor::read_from_name_and_domain(conn, &name, &domain)
558 let identifier = identifier.to_string();
559 Ok(blocking(pool, move |conn| Actor::read_from_name(conn, &identifier)).await??)
563 pub async fn remove_user_data(banned_person_id: PersonId, pool: &DbPool) -> Result<(), LemmyError> {
565 blocking(pool, move |conn: &'_ _| {
566 Post::update_removed_for_creator(conn, banned_person_id, None, true)
571 // Remove all communities where they're the top mod
572 // for now, remove the communities manually
573 let first_mod_communities = blocking(pool, move |conn: &'_ _| {
574 CommunityModeratorView::get_community_first_mods(conn)
578 // Filter to only this banned users top communities
579 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
581 .filter(|fmc| fmc.moderator.id == banned_person_id)
584 for first_mod_community in banned_user_first_communities {
585 blocking(pool, move |conn: &'_ _| {
586 Community::update_removed(conn, first_mod_community.community.id, true)
592 blocking(pool, move |conn: &'_ _| {
593 Comment::update_removed_for_creator(conn, banned_person_id, true)
600 pub async fn remove_user_data_in_community(
601 community_id: CommunityId,
602 banned_person_id: PersonId,
604 ) -> Result<(), LemmyError> {
606 blocking(pool, move |conn| {
607 Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
612 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
613 let comments = blocking(pool, move |conn| {
614 CommentQueryBuilder::create(conn)
615 .creator_id(banned_person_id)
616 .community_id(community_id)
617 .limit(std::i64::MAX)
622 for comment_view in &comments {
623 let comment_id = comment_view.comment.id;
624 blocking(pool, move |conn| {
625 Comment::update_removed(conn, comment_id, true)