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