]> Untitled Git - lemmy.git/blob - crates/api_common/src/lib.rs
2d1f1bf5047ce904ec720596bb5cac70cd93e704
[lemmy.git] / crates / api_common / src / lib.rs
1 pub mod comment;
2 pub mod community;
3 pub mod person;
4 pub mod post;
5 pub mod site;
6 pub mod websocket;
7
8 use crate::site::FederatedInstances;
9 use itertools::Itertools;
10 use lemmy_db_schema::{
11   newtypes::{CommunityId, LocalUserId, PersonId, PostId},
12   source::{
13     community::Community,
14     email_verification::{EmailVerification, EmailVerificationForm},
15     password_reset_request::PasswordResetRequest,
16     person_block::PersonBlock,
17     post::{Post, PostRead, PostReadForm},
18     registration_application::RegistrationApplication,
19     secret::Secret,
20     site::Site,
21   },
22   traits::{ApubActor, Crud, Readable},
23   DbPool,
24 };
25 use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView};
26 use lemmy_db_views_actor::{
27   community_person_ban_view::CommunityPersonBanView,
28   community_view::CommunityView,
29 };
30 use lemmy_utils::{
31   claims::Claims,
32   email::send_email,
33   settings::structs::{FederationConfig, Settings},
34   utils::generate_random_string,
35   LemmyError,
36   Sensitive,
37 };
38 use url::Url;
39
40 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
41 where
42   F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
43   T: Send + 'static,
44 {
45   let pool = pool.clone();
46   let blocking_span = tracing::info_span!("blocking operation");
47   let res = actix_web::web::block(move || {
48     let entered = blocking_span.enter();
49     let conn = pool.get()?;
50     let res = (f)(&conn);
51     drop(entered);
52     Ok(res) as Result<T, LemmyError>
53   })
54   .await?;
55
56   res
57 }
58
59 #[tracing::instrument(skip_all)]
60 pub async fn is_mod_or_admin(
61   pool: &DbPool,
62   person_id: PersonId,
63   community_id: CommunityId,
64 ) -> Result<(), LemmyError> {
65   let is_mod_or_admin = blocking(pool, move |conn| {
66     CommunityView::is_mod_or_admin(conn, person_id, community_id)
67   })
68   .await?;
69   if !is_mod_or_admin {
70     return Err(LemmyError::from_message("not_a_mod_or_admin"));
71   }
72   Ok(())
73 }
74
75 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
76   if !local_user_view.person.admin {
77     return Err(LemmyError::from_message("not_an_admin"));
78   }
79   Ok(())
80 }
81
82 #[tracing::instrument(skip_all)]
83 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
84   blocking(pool, move |conn| Post::read(conn, post_id))
85     .await?
86     .map_err(LemmyError::from)
87     .map_err(|e| e.with_message("couldnt_find_post"))
88 }
89
90 #[tracing::instrument(skip_all)]
91 pub async fn mark_post_as_read(
92   person_id: PersonId,
93   post_id: PostId,
94   pool: &DbPool,
95 ) -> Result<PostRead, LemmyError> {
96   let post_read_form = PostReadForm { post_id, person_id };
97
98   blocking(pool, move |conn| {
99     PostRead::mark_as_read(conn, &post_read_form)
100   })
101   .await?
102   .map_err(LemmyError::from)
103   .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
104 }
105
106 #[tracing::instrument(skip_all)]
107 pub async fn mark_post_as_unread(
108   person_id: PersonId,
109   post_id: PostId,
110   pool: &DbPool,
111 ) -> Result<usize, LemmyError> {
112   let post_read_form = PostReadForm { post_id, person_id };
113
114   blocking(pool, move |conn| {
115     PostRead::mark_as_unread(conn, &post_read_form)
116   })
117   .await?
118   .map_err(LemmyError::from)
119   .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
120 }
121
122 #[tracing::instrument(skip_all)]
123 pub async fn get_local_user_view_from_jwt(
124   jwt: &str,
125   pool: &DbPool,
126   secret: &Secret,
127 ) -> Result<LocalUserView, LemmyError> {
128   let claims = Claims::decode(jwt, &secret.jwt_secret)
129     .map_err(LemmyError::from)
130     .map_err(|e| e.with_message("not_logged_in"))?
131     .claims;
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"));
138   }
139
140   // Check for user deletion
141   if local_user_view.person.deleted {
142     return Err(LemmyError::from_message("deleted"));
143   }
144
145   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
146
147   Ok(local_user_view)
148 }
149
150 /// Checks if user's token was issued before user's password reset.
151 pub fn check_validator_time(
152   validator_time: &chrono::NaiveDateTime,
153   claims: &Claims,
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"))
158   } else {
159     Ok(())
160   }
161 }
162
163 #[tracing::instrument(skip_all)]
164 pub async fn get_local_user_view_from_jwt_opt(
165   jwt: Option<&Sensitive<String>>,
166   pool: &DbPool,
167   secret: &Secret,
168 ) -> Result<Option<LocalUserView>, LemmyError> {
169   match jwt {
170     Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
171     None => Ok(None),
172   }
173 }
174
175 #[tracing::instrument(skip_all)]
176 pub async fn get_local_user_settings_view_from_jwt(
177   jwt: &Sensitive<String>,
178   pool: &DbPool,
179   secret: &Secret,
180 ) -> Result<LocalUserSettingsView, LemmyError> {
181   let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
182     .map_err(LemmyError::from)
183     .map_err(|e| e.with_message("not_logged_in"))?
184     .claims;
185   let local_user_id = LocalUserId(claims.sub);
186   let local_user_view = blocking(pool, move |conn| {
187     LocalUserSettingsView::read(conn, local_user_id)
188   })
189   .await??;
190   // Check for a site ban
191   if local_user_view.person.is_banned() {
192     return Err(LemmyError::from_message("site_ban"));
193   }
194
195   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
196
197   Ok(local_user_view)
198 }
199
200 #[tracing::instrument(skip_all)]
201 pub async fn get_local_user_settings_view_from_jwt_opt(
202   jwt: Option<&Sensitive<String>>,
203   pool: &DbPool,
204   secret: &Secret,
205 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
206   match jwt {
207     Some(jwt) => Ok(Some(
208       get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
209     )),
210     None => Ok(None),
211   }
212 }
213
214 #[tracing::instrument(skip_all)]
215 pub async fn check_community_ban(
216   person_id: PersonId,
217   community_id: CommunityId,
218   pool: &DbPool,
219 ) -> Result<(), LemmyError> {
220   let is_banned =
221     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
222   if blocking(pool, is_banned).await? {
223     Err(LemmyError::from_message("community_ban"))
224   } else {
225     Ok(())
226   }
227 }
228
229 #[tracing::instrument(skip_all)]
230 pub async fn check_community_deleted_or_removed(
231   community_id: CommunityId,
232   pool: &DbPool,
233 ) -> Result<(), LemmyError> {
234   let community = blocking(pool, move |conn| Community::read(conn, community_id))
235     .await?
236     .map_err(LemmyError::from)
237     .map_err(|e| e.with_message("couldnt_find_community"))?;
238   if community.deleted || community.removed {
239     Err(LemmyError::from_message("deleted"))
240   } else {
241     Ok(())
242   }
243 }
244
245 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
246   if post.deleted || post.removed {
247     Err(LemmyError::from_message("deleted"))
248   } else {
249     Ok(())
250   }
251 }
252
253 #[tracing::instrument(skip_all)]
254 pub async fn check_person_block(
255   my_id: PersonId,
256   potential_blocker_id: PersonId,
257   pool: &DbPool,
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"))
262   } else {
263     Ok(())
264   }
265 }
266
267 #[tracing::instrument(skip_all)]
268 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
269   if score == -1 {
270     let site = blocking(pool, Site::read_simple).await??;
271     if !site.enable_downvotes {
272       return Err(LemmyError::from_message("downvotes_disabled"));
273     }
274   }
275   Ok(())
276 }
277
278 #[tracing::instrument(skip_all)]
279 pub async fn check_private_instance(
280   local_user_view: &Option<LocalUserView>,
281   pool: &DbPool,
282 ) -> Result<(), LemmyError> {
283   if local_user_view.is_none() {
284     let site = blocking(pool, Site::read_simple).await?;
285
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"));
290       }
291     }
292   }
293   Ok(())
294 }
295
296 #[tracing::instrument(skip_all)]
297 pub async fn build_federated_instances(
298   pool: &DbPool,
299   federation_config: &FederationConfig,
300   hostname: &str,
301 ) -> Result<Option<FederatedInstances>, LemmyError> {
302   let federation = federation_config.to_owned();
303   if federation.enabled {
304     let distinct_communities = blocking(pool, move |conn| {
305       Community::distinct_federated_communities(conn)
306     })
307     .await??;
308
309     let allowed = federation.allowed_instances;
310     let blocked = federation.blocked_instances;
311
312     let mut linked = distinct_communities
313       .iter()
314       .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
315       .collect::<Result<Vec<String>, LemmyError>>()?;
316
317     if let Some(allowed) = allowed.as_ref() {
318       linked.extend_from_slice(allowed);
319     }
320
321     if let Some(blocked) = blocked.as_ref() {
322       linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
323     }
324
325     // Sort and remove dupes
326     linked.sort_unstable();
327     linked.dedup();
328
329     Ok(Some(FederatedInstances {
330       linked,
331       allowed,
332       blocked,
333     }))
334   } else {
335     Ok(None)
336   }
337 }
338
339 /// Checks the password length
340 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
341   if !(10..=60).contains(&pass.len()) {
342     Err(LemmyError::from_message("invalid_password"))
343   } else {
344     Ok(())
345   }
346 }
347
348 /// Checks the site description length
349 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
350   if description.len() > 150 {
351     Err(LemmyError::from_message("site_description_length_overflow"))
352   } else {
353     Ok(())
354   }
355 }
356
357 /// Checks for a honeypot. If this field is filled, fail the rest of the function
358 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
359   if honeypot.is_some() {
360     Err(LemmyError::from_message("honeypot_fail"))
361   } else {
362     Ok(())
363   }
364 }
365
366 pub fn send_email_to_user(
367   local_user_view: &LocalUserView,
368   subject_text: &str,
369   body_text: &str,
370   comment_content: &str,
371   settings: &Settings,
372 ) {
373   if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
374     return;
375   }
376
377   if let Some(user_email) = &local_user_view.local_user.email {
378     let subject = &format!(
379       "{} - {} {}",
380       subject_text, settings.hostname, local_user_view.person.name,
381     );
382     let html = &format!(
383       "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
384       body_text,
385       local_user_view.person.name,
386       comment_content,
387       settings.get_protocol_and_hostname()
388     );
389     match send_email(
390       subject,
391       user_email,
392       &local_user_view.person.name,
393       html,
394       settings,
395     ) {
396       Ok(_o) => _o,
397       Err(e) => tracing::error!("{}", e),
398     };
399   }
400 }
401
402 pub async fn send_password_reset_email(
403   local_user_view: &LocalUserView,
404   pool: &DbPool,
405   settings: &Settings,
406 ) -> Result<(), LemmyError> {
407   // Generate a random token
408   let token = generate_random_string();
409
410   // Insert the row
411   let token2 = token.clone();
412   let local_user_id = local_user_view.local_user.id;
413   blocking(pool, move |conn| {
414     PasswordResetRequest::create_token(conn, local_user_id, &token2)
415   })
416   .await??;
417
418   let email = &local_user_view.local_user.email.to_owned().expect("email");
419   let subject = &format!("Password reset for {}", local_user_view.person.name);
420   let protocol_and_hostname = settings.get_protocol_and_hostname();
421   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);
422   send_email(subject, email, &local_user_view.person.name, html, settings)
423 }
424
425 /// Send a verification email
426 pub async fn send_verification_email(
427   local_user_id: LocalUserId,
428   new_email: &str,
429   username: &str,
430   pool: &DbPool,
431   settings: &Settings,
432 ) -> Result<(), LemmyError> {
433   let form = EmailVerificationForm {
434     local_user_id,
435     email: new_email.to_string(),
436     verification_token: generate_random_string(),
437   };
438   let verify_link = format!(
439     "{}/verify_email/{}",
440     settings.get_protocol_and_hostname(),
441     &form.verification_token
442   );
443   blocking(pool, move |conn| EmailVerification::create(conn, &form)).await??;
444
445   let subject = format!("Verify your email address for {}", settings.hostname);
446   let body = format!(
447     concat!(
448       "Please click the link below to verify your email address ",
449       "for the account @{}@{}. Ignore this email if the account isn't yours.<br><br>",
450       "<a href=\"{}\">Verify your email</a>"
451     ),
452     username, settings.hostname, verify_link
453   );
454   send_email(&subject, new_email, username, &body, settings)?;
455
456   Ok(())
457 }
458
459 pub fn send_email_verification_success(
460   local_user_view: &LocalUserView,
461   settings: &Settings,
462 ) -> Result<(), LemmyError> {
463   let email = &local_user_view.local_user.email.to_owned().expect("email");
464   let subject = &format!("Email verified for {}", local_user_view.person.actor_id);
465   let html = "Your email has been verified.";
466   send_email(subject, email, &local_user_view.person.name, html, settings)
467 }
468
469 pub fn send_application_approved_email(
470   local_user_view: &LocalUserView,
471   settings: &Settings,
472 ) -> Result<(), LemmyError> {
473   let email = &local_user_view.local_user.email.to_owned().expect("email");
474   let subject = &format!(
475     "Registration approved for {}",
476     local_user_view.person.actor_id
477   );
478   let html = &format!(
479     "Your registration application has been approved. Welcome to {}!",
480     settings.hostname
481   );
482   send_email(subject, email, &local_user_view.person.name, html, settings)
483 }
484
485 pub async fn check_registration_application(
486   site: &Site,
487   local_user_view: &LocalUserView,
488   pool: &DbPool,
489 ) -> Result<(), LemmyError> {
490   if site.require_application
491     && !local_user_view.local_user.accepted_application
492     && !local_user_view.person.admin
493   {
494     // Fetch the registration, see if its denied
495     let local_user_id = local_user_view.local_user.id;
496     let registration = blocking(pool, move |conn| {
497       RegistrationApplication::find_by_local_user_id(conn, local_user_id)
498     })
499     .await??;
500     if registration.deny_reason.is_some() {
501       return Err(LemmyError::from_message("registration_denied"));
502     } else {
503       return Err(LemmyError::from_message("registration_application_pending"));
504     }
505   }
506   Ok(())
507 }
508
509 /// TODO this check should be removed after https://github.com/LemmyNet/lemmy/issues/868 is done.
510 pub async fn check_private_instance_and_federation_enabled(
511   pool: &DbPool,
512   settings: &Settings,
513 ) -> Result<(), LemmyError> {
514   let site_opt = blocking(pool, Site::read_simple).await?;
515
516   if let Ok(site) = site_opt {
517     if site.private_instance && settings.federation.enabled {
518       return Err(LemmyError::from_message(
519         "Cannot have both private instance and federation enabled.",
520       ));
521     }
522   }
523   Ok(())
524 }
525
526 /// Resolve actor identifier (eg `!news@example.com`) from local database to avoid network requests.
527 /// This only works for local actors, and remote actors which were previously fetched (so it doesnt
528 /// trigger any new fetch).
529 #[tracing::instrument(skip_all)]
530 pub async fn resolve_actor_identifier<Actor>(
531   identifier: &str,
532   pool: &DbPool,
533 ) -> Result<Actor, LemmyError>
534 where
535   Actor: ApubActor + Send + 'static,
536 {
537   // remote actor
538   if identifier.contains('@') {
539     let (name, domain) = identifier
540       .splitn(2, '@')
541       .collect_tuple()
542       .expect("invalid query");
543     let name = name.to_string();
544     let domain = format!("{}://{}", Settings::get().get_protocol_string(), domain);
545     Ok(
546       blocking(pool, move |conn| {
547         Actor::read_from_name_and_domain(conn, &name, &domain)
548       })
549       .await??,
550     )
551   }
552   // local actor
553   else {
554     let identifier = identifier.to_string();
555     Ok(blocking(pool, move |conn| Actor::read_from_name(conn, &identifier)).await??)
556   }
557 }