1 use actix_web::{web, web::Data};
2 use lemmy_api_structs::{
11 use lemmy_db_queries::{
13 community::{CommunityModerator_, Community_},
15 user::UserSafeSettings_,
20 use lemmy_db_schema::source::{
21 community::{Community, CommunityModerator},
24 user::{UserSafeSettings, User_},
26 use lemmy_db_views_actor::{
27 community_user_ban_view::CommunityUserBanView,
28 community_view::CommunityView,
32 settings::structs::Settings,
37 use lemmy_websocket::{serialize_websocket_message, LemmyContext, UserOperation};
38 use serde::Deserialize;
39 use std::{env, process::Command};
50 #[async_trait::async_trait(?Send)]
52 type Response: serde::ser::Serialize + Send;
56 context: &Data<LemmyContext>,
57 websocket_id: Option<ConnectionId>,
58 ) -> Result<Self::Response, LemmyError>;
61 pub(crate) async fn is_mod_or_admin(
65 ) -> Result<(), LemmyError> {
66 let is_mod_or_admin = blocking(pool, move |conn| {
67 CommunityView::is_mod_or_admin(conn, user_id, community_id)
71 return Err(ApiError::err("not_a_mod_or_admin").into());
75 pub async fn is_admin(pool: &DbPool, user_id: i32) -> Result<(), LemmyError> {
76 let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
78 return Err(ApiError::err("not_an_admin").into());
83 pub(crate) async fn get_post(post_id: i32, pool: &DbPool) -> Result<Post, LemmyError> {
84 match blocking(pool, move |conn| Post::read(conn, post_id)).await? {
86 Err(_e) => Err(ApiError::err("couldnt_find_post").into()),
90 pub(crate) async fn get_user_from_jwt(jwt: &str, pool: &DbPool) -> Result<User_, LemmyError> {
91 let claims = match Claims::decode(&jwt) {
92 Ok(claims) => claims.claims,
93 Err(_e) => return Err(ApiError::err("not_logged_in").into()),
95 let user_id = claims.id;
96 let user = blocking(pool, move |conn| User_::read(conn, user_id)).await??;
97 // Check for a site ban
99 return Err(ApiError::err("site_ban").into());
101 // if user's token was issued before user's password reset.
102 let user_validation_time = user.validator_time.timestamp_millis() / 1000;
103 if user_validation_time > claims.iat {
104 return Err(ApiError::err("not_logged_in").into());
109 pub(crate) async fn get_user_from_jwt_opt(
110 jwt: &Option<String>,
112 ) -> Result<Option<User_>, LemmyError> {
114 Some(jwt) => Ok(Some(get_user_from_jwt(jwt, pool).await?)),
119 pub(crate) async fn get_user_safe_settings_from_jwt(
122 ) -> Result<UserSafeSettings, LemmyError> {
123 let claims = match Claims::decode(&jwt) {
124 Ok(claims) => claims.claims,
125 Err(_e) => return Err(ApiError::err("not_logged_in").into()),
127 let user_id = claims.id;
128 let user = blocking(pool, move |conn| UserSafeSettings::read(conn, user_id)).await??;
129 // Check for a site ban
131 return Err(ApiError::err("site_ban").into());
133 // if user's token was issued before user's password reset.
134 let user_validation_time = user.validator_time.timestamp_millis() / 1000;
135 if user_validation_time >= claims.iat {
136 return Err(ApiError::err("not_logged_in").into());
141 pub(crate) async fn get_user_safe_settings_from_jwt_opt(
142 jwt: &Option<String>,
144 ) -> Result<Option<UserSafeSettings>, LemmyError> {
146 Some(jwt) => Ok(Some(get_user_safe_settings_from_jwt(jwt, pool).await?)),
151 pub(crate) async fn check_community_ban(
155 ) -> Result<(), LemmyError> {
156 let is_banned = move |conn: &'_ _| CommunityUserBanView::get(conn, user_id, community_id).is_ok();
157 if blocking(pool, is_banned).await? {
158 Err(ApiError::err("community_ban").into())
164 pub(crate) async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
166 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
167 if !site.enable_downvotes {
168 return Err(ApiError::err("downvotes_disabled").into());
174 /// Returns a list of communities that the user moderates
175 /// or if a community_id is supplied validates the user is a moderator
176 /// of that community and returns the community id in a vec
178 /// * `user_id` - the user id of the moderator
179 /// * `community_id` - optional community id to check for moderator privileges
180 /// * `pool` - the diesel db pool
181 pub(crate) async fn collect_moderated_communities(
183 community_id: Option<i32>,
185 ) -> Result<Vec<i32>, LemmyError> {
186 if let Some(community_id) = community_id {
187 // if the user provides a community_id, just check for mod/admin privileges
188 is_mod_or_admin(pool, user_id, community_id).await?;
189 Ok(vec![community_id])
191 let ids = blocking(pool, move |conn: &'_ _| {
192 CommunityModerator::get_user_moderated_communities(conn, user_id)
199 pub(crate) async fn build_federated_instances(
201 ) -> Result<Option<FederatedInstances>, LemmyError> {
202 if Settings::get().federation().enabled {
203 let distinct_communities = blocking(pool, move |conn| {
204 Community::distinct_federated_communities(conn)
208 let allowed = Settings::get().get_allowed_instances();
209 let blocked = Settings::get().get_blocked_instances();
211 let mut linked = distinct_communities
213 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
214 .collect::<Result<Vec<String>, LemmyError>>()?;
216 if let Some(allowed) = allowed.as_ref() {
217 linked.extend_from_slice(allowed);
220 if let Some(blocked) = blocked.as_ref() {
221 linked.retain(|a| !blocked.contains(a) && !a.eq(&Settings::get().hostname()));
224 // Sort and remove dupes
225 linked.sort_unstable();
228 Ok(Some(FederatedInstances {
238 pub async fn match_websocket_operation(
239 context: LemmyContext,
243 ) -> Result<String, LemmyError> {
246 UserOperation::Login => do_websocket_operation::<Login>(context, id, op, data).await,
247 UserOperation::Register => do_websocket_operation::<Register>(context, id, op, data).await,
248 UserOperation::GetCaptcha => do_websocket_operation::<GetCaptcha>(context, id, op, data).await,
249 UserOperation::GetUserDetails => {
250 do_websocket_operation::<GetUserDetails>(context, id, op, data).await
252 UserOperation::GetReplies => do_websocket_operation::<GetReplies>(context, id, op, data).await,
253 UserOperation::AddAdmin => do_websocket_operation::<AddAdmin>(context, id, op, data).await,
254 UserOperation::BanUser => do_websocket_operation::<BanUser>(context, id, op, data).await,
255 UserOperation::GetUserMentions => {
256 do_websocket_operation::<GetUserMentions>(context, id, op, data).await
258 UserOperation::MarkUserMentionAsRead => {
259 do_websocket_operation::<MarkUserMentionAsRead>(context, id, op, data).await
261 UserOperation::MarkAllAsRead => {
262 do_websocket_operation::<MarkAllAsRead>(context, id, op, data).await
264 UserOperation::DeleteAccount => {
265 do_websocket_operation::<DeleteAccount>(context, id, op, data).await
267 UserOperation::PasswordReset => {
268 do_websocket_operation::<PasswordReset>(context, id, op, data).await
270 UserOperation::PasswordChange => {
271 do_websocket_operation::<PasswordChange>(context, id, op, data).await
273 UserOperation::UserJoin => do_websocket_operation::<UserJoin>(context, id, op, data).await,
274 UserOperation::PostJoin => do_websocket_operation::<PostJoin>(context, id, op, data).await,
275 UserOperation::CommunityJoin => {
276 do_websocket_operation::<CommunityJoin>(context, id, op, data).await
278 UserOperation::ModJoin => do_websocket_operation::<ModJoin>(context, id, op, data).await,
279 UserOperation::SaveUserSettings => {
280 do_websocket_operation::<SaveUserSettings>(context, id, op, data).await
282 UserOperation::GetReportCount => {
283 do_websocket_operation::<GetReportCount>(context, id, op, data).await
286 // Private Message ops
287 UserOperation::CreatePrivateMessage => {
288 do_websocket_operation::<CreatePrivateMessage>(context, id, op, data).await
290 UserOperation::EditPrivateMessage => {
291 do_websocket_operation::<EditPrivateMessage>(context, id, op, data).await
293 UserOperation::DeletePrivateMessage => {
294 do_websocket_operation::<DeletePrivateMessage>(context, id, op, data).await
296 UserOperation::MarkPrivateMessageAsRead => {
297 do_websocket_operation::<MarkPrivateMessageAsRead>(context, id, op, data).await
299 UserOperation::GetPrivateMessages => {
300 do_websocket_operation::<GetPrivateMessages>(context, id, op, data).await
304 UserOperation::GetModlog => do_websocket_operation::<GetModlog>(context, id, op, data).await,
305 UserOperation::CreateSite => do_websocket_operation::<CreateSite>(context, id, op, data).await,
306 UserOperation::EditSite => do_websocket_operation::<EditSite>(context, id, op, data).await,
307 UserOperation::GetSite => do_websocket_operation::<GetSite>(context, id, op, data).await,
308 UserOperation::GetSiteConfig => {
309 do_websocket_operation::<GetSiteConfig>(context, id, op, data).await
311 UserOperation::SaveSiteConfig => {
312 do_websocket_operation::<SaveSiteConfig>(context, id, op, data).await
314 UserOperation::Search => do_websocket_operation::<Search>(context, id, op, data).await,
315 UserOperation::TransferCommunity => {
316 do_websocket_operation::<TransferCommunity>(context, id, op, data).await
318 UserOperation::TransferSite => {
319 do_websocket_operation::<TransferSite>(context, id, op, data).await
323 UserOperation::GetCommunity => {
324 do_websocket_operation::<GetCommunity>(context, id, op, data).await
326 UserOperation::ListCommunities => {
327 do_websocket_operation::<ListCommunities>(context, id, op, data).await
329 UserOperation::CreateCommunity => {
330 do_websocket_operation::<CreateCommunity>(context, id, op, data).await
332 UserOperation::EditCommunity => {
333 do_websocket_operation::<EditCommunity>(context, id, op, data).await
335 UserOperation::DeleteCommunity => {
336 do_websocket_operation::<DeleteCommunity>(context, id, op, data).await
338 UserOperation::RemoveCommunity => {
339 do_websocket_operation::<RemoveCommunity>(context, id, op, data).await
341 UserOperation::FollowCommunity => {
342 do_websocket_operation::<FollowCommunity>(context, id, op, data).await
344 UserOperation::GetFollowedCommunities => {
345 do_websocket_operation::<GetFollowedCommunities>(context, id, op, data).await
347 UserOperation::BanFromCommunity => {
348 do_websocket_operation::<BanFromCommunity>(context, id, op, data).await
350 UserOperation::AddModToCommunity => {
351 do_websocket_operation::<AddModToCommunity>(context, id, op, data).await
355 UserOperation::CreatePost => do_websocket_operation::<CreatePost>(context, id, op, data).await,
356 UserOperation::GetPost => do_websocket_operation::<GetPost>(context, id, op, data).await,
357 UserOperation::GetPosts => do_websocket_operation::<GetPosts>(context, id, op, data).await,
358 UserOperation::EditPost => do_websocket_operation::<EditPost>(context, id, op, data).await,
359 UserOperation::DeletePost => do_websocket_operation::<DeletePost>(context, id, op, data).await,
360 UserOperation::RemovePost => do_websocket_operation::<RemovePost>(context, id, op, data).await,
361 UserOperation::LockPost => do_websocket_operation::<LockPost>(context, id, op, data).await,
362 UserOperation::StickyPost => do_websocket_operation::<StickyPost>(context, id, op, data).await,
363 UserOperation::CreatePostLike => {
364 do_websocket_operation::<CreatePostLike>(context, id, op, data).await
366 UserOperation::SavePost => do_websocket_operation::<SavePost>(context, id, op, data).await,
367 UserOperation::CreatePostReport => {
368 do_websocket_operation::<CreatePostReport>(context, id, op, data).await
370 UserOperation::ListPostReports => {
371 do_websocket_operation::<ListPostReports>(context, id, op, data).await
373 UserOperation::ResolvePostReport => {
374 do_websocket_operation::<ResolvePostReport>(context, id, op, data).await
378 UserOperation::CreateComment => {
379 do_websocket_operation::<CreateComment>(context, id, op, data).await
381 UserOperation::EditComment => {
382 do_websocket_operation::<EditComment>(context, id, op, data).await
384 UserOperation::DeleteComment => {
385 do_websocket_operation::<DeleteComment>(context, id, op, data).await
387 UserOperation::RemoveComment => {
388 do_websocket_operation::<RemoveComment>(context, id, op, data).await
390 UserOperation::MarkCommentAsRead => {
391 do_websocket_operation::<MarkCommentAsRead>(context, id, op, data).await
393 UserOperation::SaveComment => {
394 do_websocket_operation::<SaveComment>(context, id, op, data).await
396 UserOperation::GetComments => {
397 do_websocket_operation::<GetComments>(context, id, op, data).await
399 UserOperation::CreateCommentLike => {
400 do_websocket_operation::<CreateCommentLike>(context, id, op, data).await
402 UserOperation::CreateCommentReport => {
403 do_websocket_operation::<CreateCommentReport>(context, id, op, data).await
405 UserOperation::ListCommentReports => {
406 do_websocket_operation::<ListCommentReports>(context, id, op, data).await
408 UserOperation::ResolveCommentReport => {
409 do_websocket_operation::<ResolveCommentReport>(context, id, op, data).await
414 async fn do_websocket_operation<'a, 'b, Data>(
415 context: LemmyContext,
419 ) -> Result<String, LemmyError>
421 for<'de> Data: Deserialize<'de> + 'a,
424 let parsed_data: Data = serde_json::from_str(&data)?;
425 let res = parsed_data
426 .perform(&web::Data::new(context), Some(id))
428 serialize_websocket_message(&op, &res)
431 pub(crate) fn captcha_espeak_wav_base64(captcha: &str) -> Result<String, LemmyError> {
432 let mut built_text = String::new();
434 // Building proper speech text for espeak
435 for mut c in captcha.chars() {
436 let new_str = if c.is_alphabetic() {
437 if c.is_lowercase() {
438 c.make_ascii_uppercase();
439 format!("lower case {} ... ", c)
441 c.make_ascii_uppercase();
442 format!("capital {} ... ", c)
448 built_text.push_str(&new_str);
451 espeak_wav_base64(&built_text)
454 pub(crate) fn espeak_wav_base64(text: &str) -> Result<String, LemmyError> {
455 // Make a temp file path
456 let uuid = uuid::Uuid::new_v4().to_string();
457 let file_path = format!(
458 "{}/lemmy_espeak_{}.wav",
459 env::temp_dir().to_string_lossy(),
463 // Write the wav file
464 Command::new("espeak")
470 // Read the wav file bytes
471 let bytes = std::fs::read(&file_path)?;
474 std::fs::remove_file(file_path)?;
477 let base64 = base64::encode(bytes);
482 /// Checks the password length
483 pub(crate) fn password_length_check(pass: &str) -> Result<(), LemmyError> {
485 Err(ApiError::err("invalid_password").into())
493 use crate::{captcha_espeak_wav_base64, get_user_from_jwt};
494 use lemmy_db_queries::{
495 establish_pooled_connection,
501 use lemmy_db_schema::source::user::{UserForm, User_};
502 use lemmy_utils::claims::Claims;
504 env::{current_dir, set_current_dir},
509 async fn test_should_not_validate_user_token_after_password_change() {
510 struct CwdGuard(PathBuf);
511 impl Drop for CwdGuard {
513 let _ = set_current_dir(&self.0);
517 let _dir_bkp = CwdGuard(current_dir().unwrap());
519 // so configs could be read
520 let _ = set_current_dir("../..");
522 let conn = establish_pooled_connection();
524 let new_user = UserForm {
525 name: "user_df342sgf".into(),
526 preferred_username: None,
527 password_encrypted: "nope".into(),
529 matrix_user_id: None,
537 theme: "browser".into(),
538 default_sort_type: SortType::Hot as i16,
539 default_listing_type: ListingType::Subscribed as i16,
540 lang: "browser".into(),
542 send_notifications_to_email: false,
548 last_refreshed_at: None,
550 shared_inbox_url: None,
553 let inserted_user: User_ = User_::create(&conn.get().unwrap(), &new_user).unwrap();
555 let jwt_token = Claims::jwt(inserted_user.id, String::from("my-host.com")).unwrap();
557 get_user_from_jwt(&jwt_token, &conn)
559 .expect("User should be decoded");
561 std::thread::sleep(std::time::Duration::from_secs(1));
563 User_::update_password(&conn.get().unwrap(), inserted_user.id, &"password111").unwrap();
565 let jwt_decode_res = get_user_from_jwt(&jwt_token, &conn).await;
567 jwt_decode_res.expect_err("JWT decode should fail after password change");
572 assert!(captcha_espeak_wav_base64("WxRt2l").is_ok())