]> Untitled Git - lemmy.git/blob - crates/api_common/src/lib.rs
Don't drop error context when adding a message to errors (#1958)
[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     person_block::PersonBlock,
14     post::{Post, PostRead, PostReadForm},
15     secret::Secret,
16     site::Site,
17   },
18   traits::{Crud, Readable},
19   DbPool,
20 };
21 use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView};
22 use lemmy_db_views_actor::{
23   community_person_ban_view::CommunityPersonBanView,
24   community_view::CommunityView,
25 };
26 use lemmy_utils::{claims::Claims, settings::structs::FederationConfig, LemmyError, Sensitive};
27 use url::Url;
28
29 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
30 where
31   F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
32   T: Send + 'static,
33 {
34   let pool = pool.clone();
35   let blocking_span = tracing::info_span!("blocking operation");
36   let res = actix_web::web::block(move || {
37     let entered = blocking_span.enter();
38     let conn = pool.get()?;
39     let res = (f)(&conn);
40     drop(entered);
41     Ok(res) as Result<T, LemmyError>
42   })
43   .await?;
44
45   res
46 }
47
48 pub async fn is_mod_or_admin(
49   pool: &DbPool,
50   person_id: PersonId,
51   community_id: CommunityId,
52 ) -> Result<(), LemmyError> {
53   let is_mod_or_admin = blocking(pool, move |conn| {
54     CommunityView::is_mod_or_admin(conn, person_id, community_id)
55   })
56   .await?;
57   if !is_mod_or_admin {
58     return Err(LemmyError::from_message("not_a_mod_or_admin"));
59   }
60   Ok(())
61 }
62
63 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
64   if !local_user_view.person.admin {
65     return Err(LemmyError::from_message("not_an_admin"));
66   }
67   Ok(())
68 }
69
70 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
71   blocking(pool, move |conn| Post::read(conn, post_id))
72     .await?
73     .map_err(LemmyError::from)
74     .map_err(|e| e.with_message("couldnt_find_post"))
75 }
76
77 pub async fn mark_post_as_read(
78   person_id: PersonId,
79   post_id: PostId,
80   pool: &DbPool,
81 ) -> Result<PostRead, LemmyError> {
82   let post_read_form = PostReadForm { post_id, person_id };
83
84   blocking(pool, move |conn| {
85     PostRead::mark_as_read(conn, &post_read_form)
86   })
87   .await?
88   .map_err(LemmyError::from)
89   .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
90 }
91
92 pub async fn mark_post_as_unread(
93   person_id: PersonId,
94   post_id: PostId,
95   pool: &DbPool,
96 ) -> Result<usize, LemmyError> {
97   let post_read_form = PostReadForm { post_id, person_id };
98
99   blocking(pool, move |conn| {
100     PostRead::mark_as_unread(conn, &post_read_form)
101   })
102   .await?
103   .map_err(LemmyError::from)
104   .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
105 }
106
107 pub async fn get_local_user_view_from_jwt(
108   jwt: &str,
109   pool: &DbPool,
110   secret: &Secret,
111 ) -> Result<LocalUserView, LemmyError> {
112   let claims = Claims::decode(jwt, &secret.jwt_secret)
113     .map_err(LemmyError::from)
114     .map_err(|e| e.with_message("not_logged_in"))?
115     .claims;
116   let local_user_id = LocalUserId(claims.sub);
117   let local_user_view =
118     blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
119   // Check for a site ban
120   if local_user_view.person.banned {
121     return Err(LemmyError::from_message("site_ban"));
122   }
123
124   // Check for user deletion
125   if local_user_view.person.deleted {
126     return Err(LemmyError::from_message("deleted"));
127   }
128
129   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
130
131   Ok(local_user_view)
132 }
133
134 /// Checks if user's token was issued before user's password reset.
135 pub fn check_validator_time(
136   validator_time: &chrono::NaiveDateTime,
137   claims: &Claims,
138 ) -> Result<(), LemmyError> {
139   let user_validation_time = validator_time.timestamp();
140   if user_validation_time > claims.iat {
141     Err(LemmyError::from_message("not_logged_in"))
142   } else {
143     Ok(())
144   }
145 }
146
147 pub async fn get_local_user_view_from_jwt_opt(
148   jwt: Option<&Sensitive<String>>,
149   pool: &DbPool,
150   secret: &Secret,
151 ) -> Result<Option<LocalUserView>, LemmyError> {
152   match jwt {
153     Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
154     None => Ok(None),
155   }
156 }
157
158 pub async fn get_local_user_settings_view_from_jwt(
159   jwt: &Sensitive<String>,
160   pool: &DbPool,
161   secret: &Secret,
162 ) -> Result<LocalUserSettingsView, LemmyError> {
163   let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
164     .map_err(LemmyError::from)
165     .map_err(|e| e.with_message("not_logged_in"))?
166     .claims;
167   let local_user_id = LocalUserId(claims.sub);
168   let local_user_view = blocking(pool, move |conn| {
169     LocalUserSettingsView::read(conn, local_user_id)
170   })
171   .await??;
172   // Check for a site ban
173   if local_user_view.person.banned {
174     return Err(LemmyError::from_message("site_ban"));
175   }
176
177   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
178
179   Ok(local_user_view)
180 }
181
182 pub async fn get_local_user_settings_view_from_jwt_opt(
183   jwt: Option<&Sensitive<String>>,
184   pool: &DbPool,
185   secret: &Secret,
186 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
187   match jwt {
188     Some(jwt) => Ok(Some(
189       get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
190     )),
191     None => Ok(None),
192   }
193 }
194
195 pub async fn check_community_ban(
196   person_id: PersonId,
197   community_id: CommunityId,
198   pool: &DbPool,
199 ) -> Result<(), LemmyError> {
200   let is_banned =
201     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
202   if blocking(pool, is_banned).await? {
203     Err(LemmyError::from_message("community_ban"))
204   } else {
205     Ok(())
206   }
207 }
208
209 pub async fn check_community_deleted_or_removed(
210   community_id: CommunityId,
211   pool: &DbPool,
212 ) -> Result<(), LemmyError> {
213   let community = blocking(pool, move |conn| Community::read(conn, community_id))
214     .await?
215     .map_err(LemmyError::from)
216     .map_err(|e| e.with_message("couldnt_find_community"))?;
217   if community.deleted || community.removed {
218     Err(LemmyError::from_message("deleted"))
219   } else {
220     Ok(())
221   }
222 }
223
224 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
225   if post.deleted || post.removed {
226     Err(LemmyError::from_message("deleted"))
227   } else {
228     Ok(())
229   }
230 }
231
232 pub async fn check_person_block(
233   my_id: PersonId,
234   potential_blocker_id: PersonId,
235   pool: &DbPool,
236 ) -> Result<(), LemmyError> {
237   let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
238   if blocking(pool, is_blocked).await? {
239     Err(LemmyError::from_message("person_block"))
240   } else {
241     Ok(())
242   }
243 }
244
245 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
246   if score == -1 {
247     let site = blocking(pool, Site::read_simple).await??;
248     if !site.enable_downvotes {
249       return Err(LemmyError::from_message("downvotes_disabled"));
250     }
251   }
252   Ok(())
253 }
254
255 pub async fn build_federated_instances(
256   pool: &DbPool,
257   federation_config: &FederationConfig,
258   hostname: &str,
259 ) -> Result<Option<FederatedInstances>, LemmyError> {
260   let federation = federation_config.to_owned();
261   if federation.enabled {
262     let distinct_communities = blocking(pool, move |conn| {
263       Community::distinct_federated_communities(conn)
264     })
265     .await??;
266
267     let allowed = federation.allowed_instances;
268     let blocked = federation.blocked_instances;
269
270     let mut linked = distinct_communities
271       .iter()
272       .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
273       .collect::<Result<Vec<String>, LemmyError>>()?;
274
275     if let Some(allowed) = allowed.as_ref() {
276       linked.extend_from_slice(allowed);
277     }
278
279     if let Some(blocked) = blocked.as_ref() {
280       linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
281     }
282
283     // Sort and remove dupes
284     linked.sort_unstable();
285     linked.dedup();
286
287     Ok(Some(FederatedInstances {
288       linked,
289       allowed,
290       blocked,
291     }))
292   } else {
293     Ok(None)
294   }
295 }
296
297 /// Checks the password length
298 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
299   if !(10..=60).contains(&pass.len()) {
300     Err(LemmyError::from_message("invalid_password"))
301   } else {
302     Ok(())
303   }
304 }
305
306 /// Checks the site description length
307 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
308   if description.len() > 150 {
309     Err(LemmyError::from_message("site_description_length_overflow"))
310   } else {
311     Ok(())
312   }
313 }
314
315 /// Checks for a honeypot. If this field is filled, fail the rest of the function
316 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
317   if honeypot.is_some() {
318     Err(LemmyError::from_message("honeypot_fail"))
319   } else {
320     Ok(())
321   }
322 }