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 pub async fn is_mod_or_admin(
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)
68 return Err(LemmyError::from_message("not_a_mod_or_admin"));
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"));
80 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
81 blocking(pool, move |conn| Post::read(conn, post_id))
83 .map_err(LemmyError::from)
84 .map_err(|e| e.with_message("couldnt_find_post"))
87 pub async fn mark_post_as_read(
91 ) -> Result<PostRead, LemmyError> {
92 let post_read_form = PostReadForm { post_id, person_id };
94 blocking(pool, move |conn| {
95 PostRead::mark_as_read(conn, &post_read_form)
98 .map_err(LemmyError::from)
99 .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
102 pub async fn mark_post_as_unread(
106 ) -> Result<usize, LemmyError> {
107 let post_read_form = PostReadForm { post_id, person_id };
109 blocking(pool, move |conn| {
110 PostRead::mark_as_unread(conn, &post_read_form)
113 .map_err(LemmyError::from)
114 .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
117 pub async fn get_local_user_view_from_jwt(
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"))?
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"));
134 // Check for user deletion
135 if local_user_view.person.deleted {
136 return Err(LemmyError::from_message("deleted"));
139 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
144 /// Checks if user's token was issued before user's password reset.
145 pub fn check_validator_time(
146 validator_time: &chrono::NaiveDateTime,
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"))
157 pub async fn get_local_user_view_from_jwt_opt(
158 jwt: Option<&Sensitive<String>>,
161 ) -> Result<Option<LocalUserView>, LemmyError> {
163 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
168 pub async fn get_local_user_settings_view_from_jwt(
169 jwt: &Sensitive<String>,
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"))?
177 let local_user_id = LocalUserId(claims.sub);
178 let local_user_view = blocking(pool, move |conn| {
179 LocalUserSettingsView::read(conn, local_user_id)
182 // Check for a site ban
183 if local_user_view.person.banned {
184 return Err(LemmyError::from_message("site_ban"));
187 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
192 pub async fn get_local_user_settings_view_from_jwt_opt(
193 jwt: Option<&Sensitive<String>>,
196 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
198 Some(jwt) => Ok(Some(
199 get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
205 pub async fn check_community_ban(
207 community_id: CommunityId,
209 ) -> Result<(), LemmyError> {
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"))
219 pub async fn check_community_deleted_or_removed(
220 community_id: CommunityId,
222 ) -> Result<(), LemmyError> {
223 let community = blocking(pool, move |conn| Community::read(conn, community_id))
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"))
234 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
235 if post.deleted || post.removed {
236 Err(LemmyError::from_message("deleted"))
242 pub async fn check_person_block(
244 potential_blocker_id: PersonId,
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"))
255 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
257 let site = blocking(pool, Site::read_simple).await??;
258 if !site.enable_downvotes {
259 return Err(LemmyError::from_message("downvotes_disabled"));
265 pub async fn check_private_instance(
266 local_user_view: &Option<LocalUserView>,
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"));
278 pub async fn build_federated_instances(
280 federation_config: &FederationConfig,
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)
290 let allowed = federation.allowed_instances;
291 let blocked = federation.blocked_instances;
293 let mut linked = distinct_communities
295 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
296 .collect::<Result<Vec<String>, LemmyError>>()?;
298 if let Some(allowed) = allowed.as_ref() {
299 linked.extend_from_slice(allowed);
302 if let Some(blocked) = blocked.as_ref() {
303 linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
306 // Sort and remove dupes
307 linked.sort_unstable();
310 Ok(Some(FederatedInstances {
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"))
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"))
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"))
347 pub fn send_email_to_user(
348 local_user_view: &LocalUserView,
351 comment_content: &str,
354 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
358 if let Some(user_email) = &local_user_view.local_user.email {
359 let subject = &format!(
361 subject_text, settings.hostname, local_user_view.person.name,
364 "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
366 local_user_view.person.name,
368 settings.get_protocol_and_hostname()
373 &local_user_view.person.name,
378 Err(e) => tracing::error!("{}", e),
383 pub async fn send_password_reset_email(
384 local_user_view: &LocalUserView,
387 ) -> Result<(), LemmyError> {
388 // Generate a random token
389 let token = generate_random_string();
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)
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)
406 /// Send a verification email
407 pub async fn send_verification_email(
408 local_user_id: LocalUserId,
413 ) -> Result<(), LemmyError> {
414 let form = EmailVerificationForm {
416 email: new_email.to_string(),
417 verification_token: generate_random_string(),
419 let verify_link = format!(
420 "{}/verify_email/{}",
421 settings.get_protocol_and_hostname(),
422 &form.verification_token
424 blocking(pool, move |conn| EmailVerification::create(conn, &form)).await??;
426 let subject = format!("Verify your email address for {}", settings.hostname);
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>"
433 username, settings.hostname, verify_link
435 send_email(&subject, new_email, username, &body, settings)?;
440 pub fn send_email_verification_success(
441 local_user_view: &LocalUserView,
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)
450 pub fn send_application_approved_email(
451 local_user_view: &LocalUserView,
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
460 "Your registration application has been approved. Welcome to {}!",
463 send_email(subject, email, &local_user_view.person.name, html, settings)
466 pub async fn check_registration_application(
468 local_user_view: &LocalUserView,
470 ) -> Result<(), LemmyError> {
471 if site.require_application
472 && !local_user_view.local_user.accepted_application
473 && !local_user_view.person.admin
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)
481 if registration.deny_reason.is_some() {
482 return Err(LemmyError::from_message("registration_denied"));
484 return Err(LemmyError::from_message("registration_application_pending"));
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(
494 ) -> Result<(), LemmyError> {
495 let site_opt = blocking(pool, Site::read_simple).await?;
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.",