8 use crate::site::FederatedInstances;
10 newtypes::{CommunityId, LocalUserId, PersonId, PostId},
13 email_verification::{EmailVerification, EmailVerificationForm},
14 password_reset_request::PasswordResetRequest,
15 person_block::PersonBlock,
16 post::{Post, PostRead, PostReadForm},
17 registration_application::RegistrationApplication,
21 traits::{Crud, Readable},
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,
32 settings::structs::{FederationConfig, Settings},
33 utils::generate_random_string,
39 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
41 F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
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()?;
51 Ok(res) as Result<T, LemmyError>
58 #[tracing::instrument(skip_all)]
59 pub async fn is_mod_or_admin(
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)
69 return Err(LemmyError::from_message("not_a_mod_or_admin"));
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"));
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))
85 .map_err(LemmyError::from)
86 .map_err(|e| e.with_message("couldnt_find_post"))
89 #[tracing::instrument(skip_all)]
90 pub async fn mark_post_as_read(
94 ) -> Result<PostRead, LemmyError> {
95 let post_read_form = PostReadForm { post_id, person_id };
97 blocking(pool, move |conn| {
98 PostRead::mark_as_read(conn, &post_read_form)
101 .map_err(LemmyError::from)
102 .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
105 #[tracing::instrument(skip_all)]
106 pub async fn mark_post_as_unread(
110 ) -> Result<usize, LemmyError> {
111 let post_read_form = PostReadForm { post_id, person_id };
113 blocking(pool, move |conn| {
114 PostRead::mark_as_unread(conn, &post_read_form)
117 .map_err(LemmyError::from)
118 .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
121 #[tracing::instrument(skip_all)]
122 pub async fn get_local_user_view_from_jwt(
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"))?
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.is_banned() {
136 return Err(LemmyError::from_message("site_ban"));
139 // Check for user deletion
140 if local_user_view.person.deleted {
141 return Err(LemmyError::from_message("deleted"));
144 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
149 /// Checks if user's token was issued before user's password reset.
150 pub fn check_validator_time(
151 validator_time: &chrono::NaiveDateTime,
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"))
162 #[tracing::instrument(skip_all)]
163 pub async fn get_local_user_view_from_jwt_opt(
164 jwt: Option<&Sensitive<String>>,
167 ) -> Result<Option<LocalUserView>, LemmyError> {
169 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
174 #[tracing::instrument(skip_all)]
175 pub async fn get_local_user_settings_view_from_jwt(
176 jwt: &Sensitive<String>,
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"))?
184 let local_user_id = LocalUserId(claims.sub);
185 let local_user_view = blocking(pool, move |conn| {
186 LocalUserSettingsView::read(conn, local_user_id)
189 // Check for a site ban
190 if local_user_view.person.is_banned() {
191 return Err(LemmyError::from_message("site_ban"));
194 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
199 #[tracing::instrument(skip_all)]
200 pub async fn get_local_user_settings_view_from_jwt_opt(
201 jwt: Option<&Sensitive<String>>,
204 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
206 Some(jwt) => Ok(Some(
207 get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
213 #[tracing::instrument(skip_all)]
214 pub async fn check_community_ban(
216 community_id: CommunityId,
218 ) -> Result<(), LemmyError> {
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"))
228 #[tracing::instrument(skip_all)]
229 pub async fn check_community_deleted_or_removed(
230 community_id: CommunityId,
232 ) -> Result<(), LemmyError> {
233 let community = blocking(pool, move |conn| Community::read(conn, community_id))
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"))
244 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
245 if post.deleted || post.removed {
246 Err(LemmyError::from_message("deleted"))
252 #[tracing::instrument(skip_all)]
253 pub async fn check_person_block(
255 potential_blocker_id: PersonId,
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"))
266 #[tracing::instrument(skip_all)]
267 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
269 let site = blocking(pool, Site::read_simple).await??;
270 if !site.enable_downvotes {
271 return Err(LemmyError::from_message("downvotes_disabled"));
277 #[tracing::instrument(skip_all)]
278 pub async fn check_private_instance(
279 local_user_view: &Option<LocalUserView>,
281 ) -> Result<(), LemmyError> {
282 if local_user_view.is_none() {
283 let site = blocking(pool, Site::read_simple).await?;
285 // The site might not be set up yet
286 if let Ok(site) = site {
287 if site.private_instance {
288 return Err(LemmyError::from_message("instance_is_private"));
295 #[tracing::instrument(skip_all)]
296 pub async fn build_federated_instances(
298 federation_config: &FederationConfig,
300 ) -> Result<Option<FederatedInstances>, LemmyError> {
301 let federation = federation_config.to_owned();
302 if federation.enabled {
303 let distinct_communities = blocking(pool, move |conn| {
304 Community::distinct_federated_communities(conn)
308 let allowed = federation.allowed_instances;
309 let blocked = federation.blocked_instances;
311 let mut linked = distinct_communities
313 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
314 .collect::<Result<Vec<String>, LemmyError>>()?;
316 if let Some(allowed) = allowed.as_ref() {
317 linked.extend_from_slice(allowed);
320 if let Some(blocked) = blocked.as_ref() {
321 linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
324 // Sort and remove dupes
325 linked.sort_unstable();
328 Ok(Some(FederatedInstances {
338 /// Checks the password length
339 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
340 if !(10..=60).contains(&pass.len()) {
341 Err(LemmyError::from_message("invalid_password"))
347 /// Checks the site description length
348 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
349 if description.len() > 150 {
350 Err(LemmyError::from_message("site_description_length_overflow"))
356 /// Checks for a honeypot. If this field is filled, fail the rest of the function
357 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
358 if honeypot.is_some() {
359 Err(LemmyError::from_message("honeypot_fail"))
365 pub fn send_email_to_user(
366 local_user_view: &LocalUserView,
369 comment_content: &str,
372 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
376 if let Some(user_email) = &local_user_view.local_user.email {
377 let subject = &format!(
379 subject_text, settings.hostname, local_user_view.person.name,
382 "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
384 local_user_view.person.name,
386 settings.get_protocol_and_hostname()
391 &local_user_view.person.name,
396 Err(e) => tracing::error!("{}", e),
401 pub async fn send_password_reset_email(
402 local_user_view: &LocalUserView,
405 ) -> Result<(), LemmyError> {
406 // Generate a random token
407 let token = generate_random_string();
410 let token2 = token.clone();
411 let local_user_id = local_user_view.local_user.id;
412 blocking(pool, move |conn| {
413 PasswordResetRequest::create_token(conn, local_user_id, &token2)
417 let email = &local_user_view.local_user.email.to_owned().expect("email");
418 let subject = &format!("Password reset for {}", local_user_view.person.name);
419 let protocol_and_hostname = settings.get_protocol_and_hostname();
420 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);
421 send_email(subject, email, &local_user_view.person.name, html, settings)
424 /// Send a verification email
425 pub async fn send_verification_email(
426 local_user_id: LocalUserId,
431 ) -> Result<(), LemmyError> {
432 let form = EmailVerificationForm {
434 email: new_email.to_string(),
435 verification_token: generate_random_string(),
437 let verify_link = format!(
438 "{}/verify_email/{}",
439 settings.get_protocol_and_hostname(),
440 &form.verification_token
442 blocking(pool, move |conn| EmailVerification::create(conn, &form)).await??;
444 let subject = format!("Verify your email address for {}", settings.hostname);
447 "Please click the link below to verify your email address ",
448 "for the account @{}@{}. Ignore this email if the account isn't yours.<br><br>",
449 "<a href=\"{}\">Verify your email</a>"
451 username, settings.hostname, verify_link
453 send_email(&subject, new_email, username, &body, settings)?;
458 pub fn send_email_verification_success(
459 local_user_view: &LocalUserView,
461 ) -> Result<(), LemmyError> {
462 let email = &local_user_view.local_user.email.to_owned().expect("email");
463 let subject = &format!("Email verified for {}", local_user_view.person.actor_id);
464 let html = "Your email has been verified.";
465 send_email(subject, email, &local_user_view.person.name, html, settings)
468 pub fn send_application_approved_email(
469 local_user_view: &LocalUserView,
471 ) -> Result<(), LemmyError> {
472 let email = &local_user_view.local_user.email.to_owned().expect("email");
473 let subject = &format!(
474 "Registration approved for {}",
475 local_user_view.person.actor_id
478 "Your registration application has been approved. Welcome to {}!",
481 send_email(subject, email, &local_user_view.person.name, html, settings)
484 pub async fn check_registration_application(
486 local_user_view: &LocalUserView,
488 ) -> Result<(), LemmyError> {
489 if site.require_application
490 && !local_user_view.local_user.accepted_application
491 && !local_user_view.person.admin
493 // Fetch the registration, see if its denied
494 let local_user_id = local_user_view.local_user.id;
495 let registration = blocking(pool, move |conn| {
496 RegistrationApplication::find_by_local_user_id(conn, local_user_id)
499 if registration.deny_reason.is_some() {
500 return Err(LemmyError::from_message("registration_denied"));
502 return Err(LemmyError::from_message("registration_application_pending"));
508 /// TODO this check should be removed after https://github.com/LemmyNet/lemmy/issues/868 is done.
509 pub async fn check_private_instance_and_federation_enabled(
512 ) -> Result<(), LemmyError> {
513 let site_opt = blocking(pool, Site::read_simple).await?;
515 if let Ok(site) = site_opt {
516 if site.private_instance && settings.federation.enabled {
517 return Err(LemmyError::from_message(
518 "Cannot have both private instance and federation enabled.",