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