8 use crate::site::FederatedInstances;
9 use itertools::Itertools;
10 use lemmy_db_schema::{
11 newtypes::{CommunityId, LocalUserId, PersonId, PostId},
14 email_verification::{EmailVerification, EmailVerificationForm},
15 password_reset_request::PasswordResetRequest,
16 person_block::PersonBlock,
17 post::{Post, PostRead, PostReadForm},
18 registration_application::RegistrationApplication,
22 traits::{ApubActor, Crud, Readable},
25 use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView};
26 use lemmy_db_views_actor::{
27 community_person_ban_view::CommunityPersonBanView,
28 community_view::CommunityView,
33 settings::structs::{FederationConfig, Settings},
34 utils::generate_random_string,
40 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
42 F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
45 let pool = pool.clone();
46 let blocking_span = tracing::info_span!("blocking operation");
47 let res = actix_web::web::block(move || {
48 let entered = blocking_span.enter();
49 let conn = pool.get()?;
52 Ok(res) as Result<T, LemmyError>
59 #[tracing::instrument(skip_all)]
60 pub async fn is_mod_or_admin(
63 community_id: CommunityId,
64 ) -> Result<(), LemmyError> {
65 let is_mod_or_admin = blocking(pool, move |conn| {
66 CommunityView::is_mod_or_admin(conn, person_id, community_id)
70 return Err(LemmyError::from_message("not_a_mod_or_admin"));
75 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
76 if !local_user_view.person.admin {
77 return Err(LemmyError::from_message("not_an_admin"));
82 #[tracing::instrument(skip_all)]
83 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
84 blocking(pool, move |conn| Post::read(conn, post_id))
86 .map_err(LemmyError::from)
87 .map_err(|e| e.with_message("couldnt_find_post"))
90 #[tracing::instrument(skip_all)]
91 pub async fn mark_post_as_read(
95 ) -> Result<PostRead, LemmyError> {
96 let post_read_form = PostReadForm { post_id, person_id };
98 blocking(pool, move |conn| {
99 PostRead::mark_as_read(conn, &post_read_form)
102 .map_err(LemmyError::from)
103 .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
106 #[tracing::instrument(skip_all)]
107 pub async fn mark_post_as_unread(
111 ) -> Result<usize, LemmyError> {
112 let post_read_form = PostReadForm { post_id, person_id };
114 blocking(pool, move |conn| {
115 PostRead::mark_as_unread(conn, &post_read_form)
118 .map_err(LemmyError::from)
119 .map_err(|e| e.with_message("couldnt_mark_post_as_read"))
122 #[tracing::instrument(skip_all)]
123 pub async fn get_local_user_view_from_jwt(
127 ) -> Result<LocalUserView, LemmyError> {
128 let claims = Claims::decode(jwt, &secret.jwt_secret)
129 .map_err(LemmyError::from)
130 .map_err(|e| e.with_message("not_logged_in"))?
132 let local_user_id = LocalUserId(claims.sub);
133 let local_user_view =
134 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
135 // Check for a site ban
136 if local_user_view.person.is_banned() {
137 return Err(LemmyError::from_message("site_ban"));
140 // Check for user deletion
141 if local_user_view.person.deleted {
142 return Err(LemmyError::from_message("deleted"));
145 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
150 /// Checks if user's token was issued before user's password reset.
151 pub fn check_validator_time(
152 validator_time: &chrono::NaiveDateTime,
154 ) -> Result<(), LemmyError> {
155 let user_validation_time = validator_time.timestamp();
156 if user_validation_time > claims.iat {
157 Err(LemmyError::from_message("not_logged_in"))
163 #[tracing::instrument(skip_all)]
164 pub async fn get_local_user_view_from_jwt_opt(
165 jwt: Option<&Sensitive<String>>,
168 ) -> Result<Option<LocalUserView>, LemmyError> {
170 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
175 #[tracing::instrument(skip_all)]
176 pub async fn get_local_user_settings_view_from_jwt(
177 jwt: &Sensitive<String>,
180 ) -> Result<LocalUserSettingsView, LemmyError> {
181 let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
182 .map_err(LemmyError::from)
183 .map_err(|e| e.with_message("not_logged_in"))?
185 let local_user_id = LocalUserId(claims.sub);
186 let local_user_view = blocking(pool, move |conn| {
187 LocalUserSettingsView::read(conn, local_user_id)
190 // Check for a site ban
191 if local_user_view.person.is_banned() {
192 return Err(LemmyError::from_message("site_ban"));
195 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
200 #[tracing::instrument(skip_all)]
201 pub async fn get_local_user_settings_view_from_jwt_opt(
202 jwt: Option<&Sensitive<String>>,
205 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
207 Some(jwt) => Ok(Some(
208 get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
214 #[tracing::instrument(skip_all)]
215 pub async fn check_community_ban(
217 community_id: CommunityId,
219 ) -> Result<(), LemmyError> {
221 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
222 if blocking(pool, is_banned).await? {
223 Err(LemmyError::from_message("community_ban"))
229 #[tracing::instrument(skip_all)]
230 pub async fn check_community_deleted_or_removed(
231 community_id: CommunityId,
233 ) -> Result<(), LemmyError> {
234 let community = blocking(pool, move |conn| Community::read(conn, community_id))
236 .map_err(LemmyError::from)
237 .map_err(|e| e.with_message("couldnt_find_community"))?;
238 if community.deleted || community.removed {
239 Err(LemmyError::from_message("deleted"))
245 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
246 if post.deleted || post.removed {
247 Err(LemmyError::from_message("deleted"))
253 #[tracing::instrument(skip_all)]
254 pub async fn check_person_block(
256 potential_blocker_id: PersonId,
258 ) -> Result<(), LemmyError> {
259 let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
260 if blocking(pool, is_blocked).await? {
261 Err(LemmyError::from_message("person_block"))
267 #[tracing::instrument(skip_all)]
268 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
270 let site = blocking(pool, Site::read_simple).await??;
271 if !site.enable_downvotes {
272 return Err(LemmyError::from_message("downvotes_disabled"));
278 #[tracing::instrument(skip_all)]
279 pub async fn check_private_instance(
280 local_user_view: &Option<LocalUserView>,
282 ) -> Result<(), LemmyError> {
283 if local_user_view.is_none() {
284 let site = blocking(pool, Site::read_simple).await?;
286 // The site might not be set up yet
287 if let Ok(site) = site {
288 if site.private_instance {
289 return Err(LemmyError::from_message("instance_is_private"));
296 #[tracing::instrument(skip_all)]
297 pub async fn build_federated_instances(
299 federation_config: &FederationConfig,
301 ) -> Result<Option<FederatedInstances>, LemmyError> {
302 let federation = federation_config.to_owned();
303 if federation.enabled {
304 let distinct_communities = blocking(pool, move |conn| {
305 Community::distinct_federated_communities(conn)
309 let allowed = federation.allowed_instances;
310 let blocked = federation.blocked_instances;
312 let mut linked = distinct_communities
314 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
315 .collect::<Result<Vec<String>, LemmyError>>()?;
317 if let Some(allowed) = allowed.as_ref() {
318 linked.extend_from_slice(allowed);
321 if let Some(blocked) = blocked.as_ref() {
322 linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
325 // Sort and remove dupes
326 linked.sort_unstable();
329 Ok(Some(FederatedInstances {
339 /// Checks the password length
340 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
341 if !(10..=60).contains(&pass.len()) {
342 Err(LemmyError::from_message("invalid_password"))
348 /// Checks the site description length
349 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
350 if description.len() > 150 {
351 Err(LemmyError::from_message("site_description_length_overflow"))
357 /// Checks for a honeypot. If this field is filled, fail the rest of the function
358 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
359 if honeypot.is_some() {
360 Err(LemmyError::from_message("honeypot_fail"))
366 pub fn send_email_to_user(
367 local_user_view: &LocalUserView,
370 comment_content: &str,
373 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
377 if let Some(user_email) = &local_user_view.local_user.email {
378 let subject = &format!(
380 subject_text, settings.hostname, local_user_view.person.name,
383 "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
385 local_user_view.person.name,
387 settings.get_protocol_and_hostname()
392 &local_user_view.person.name,
397 Err(e) => tracing::error!("{}", e),
402 pub async fn send_password_reset_email(
403 local_user_view: &LocalUserView,
406 ) -> Result<(), LemmyError> {
407 // Generate a random token
408 let token = generate_random_string();
411 let token2 = token.clone();
412 let local_user_id = local_user_view.local_user.id;
413 blocking(pool, move |conn| {
414 PasswordResetRequest::create_token(conn, local_user_id, &token2)
418 let email = &local_user_view.local_user.email.to_owned().expect("email");
419 let subject = &format!("Password reset for {}", local_user_view.person.name);
420 let protocol_and_hostname = settings.get_protocol_and_hostname();
421 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);
422 send_email(subject, email, &local_user_view.person.name, html, settings)
425 /// Send a verification email
426 pub async fn send_verification_email(
427 local_user_id: LocalUserId,
432 ) -> Result<(), LemmyError> {
433 let form = EmailVerificationForm {
435 email: new_email.to_string(),
436 verification_token: generate_random_string(),
438 let verify_link = format!(
439 "{}/verify_email/{}",
440 settings.get_protocol_and_hostname(),
441 &form.verification_token
443 blocking(pool, move |conn| EmailVerification::create(conn, &form)).await??;
445 let subject = format!("Verify your email address for {}", settings.hostname);
448 "Please click the link below to verify your email address ",
449 "for the account @{}@{}. Ignore this email if the account isn't yours.<br><br>",
450 "<a href=\"{}\">Verify your email</a>"
452 username, settings.hostname, verify_link
454 send_email(&subject, new_email, username, &body, settings)?;
459 pub fn send_email_verification_success(
460 local_user_view: &LocalUserView,
462 ) -> Result<(), LemmyError> {
463 let email = &local_user_view.local_user.email.to_owned().expect("email");
464 let subject = &format!("Email verified for {}", local_user_view.person.actor_id);
465 let html = "Your email has been verified.";
466 send_email(subject, email, &local_user_view.person.name, html, settings)
469 pub fn send_application_approved_email(
470 local_user_view: &LocalUserView,
472 ) -> Result<(), LemmyError> {
473 let email = &local_user_view.local_user.email.to_owned().expect("email");
474 let subject = &format!(
475 "Registration approved for {}",
476 local_user_view.person.actor_id
479 "Your registration application has been approved. Welcome to {}!",
482 send_email(subject, email, &local_user_view.person.name, html, settings)
485 pub async fn check_registration_application(
487 local_user_view: &LocalUserView,
489 ) -> Result<(), LemmyError> {
490 if site.require_application
491 && !local_user_view.local_user.accepted_application
492 && !local_user_view.person.admin
494 // Fetch the registration, see if its denied
495 let local_user_id = local_user_view.local_user.id;
496 let registration = blocking(pool, move |conn| {
497 RegistrationApplication::find_by_local_user_id(conn, local_user_id)
500 if registration.deny_reason.is_some() {
501 return Err(LemmyError::from_message("registration_denied"));
503 return Err(LemmyError::from_message("registration_application_pending"));
509 /// TODO this check should be removed after https://github.com/LemmyNet/lemmy/issues/868 is done.
510 pub async fn check_private_instance_and_federation_enabled(
513 ) -> Result<(), LemmyError> {
514 let site_opt = blocking(pool, Site::read_simple).await?;
516 if let Ok(site) = site_opt {
517 if site.private_instance && settings.federation.enabled {
518 return Err(LemmyError::from_message(
519 "Cannot have both private instance and federation enabled.",
526 /// Resolve actor identifier (eg `!news@example.com`) from local database to avoid network requests.
527 /// This only works for local actors, and remote actors which were previously fetched (so it doesnt
528 /// trigger any new fetch).
529 #[tracing::instrument(skip_all)]
530 pub async fn resolve_actor_identifier<Actor>(
533 ) -> Result<Actor, LemmyError>
535 Actor: ApubActor + Send + 'static,
538 if identifier.contains('@') {
539 let (name, domain) = identifier
542 .expect("invalid query");
543 let name = name.to_string();
544 let domain = format!("{}://{}", Settings::get().get_protocol_string(), domain);
546 blocking(pool, move |conn| {
547 Actor::read_from_name_and_domain(conn, &name, &domain)
554 let identifier = identifier.to_string();
555 Ok(blocking(pool, move |conn| Actor::read_from_name(conn, &identifier)).await??)