1 use crate::{captcha_as_wav_base64, Perform};
2 use actix_web::web::Data;
5 use captcha::{gen, Difficulty};
7 use lemmy_api_common::{
9 collect_moderated_communities,
10 get_local_user_view_from_jwt,
12 password_length_check,
15 use lemmy_db_queries::{
16 diesel_option_overwrite,
17 diesel_option_overwrite_to_url,
18 from_opt_str_to_opt_enum,
21 community::Community_,
22 local_user::LocalUser_,
23 password_reset_request::PasswordResetRequest_,
25 person_mention::PersonMention_,
27 private_message::PrivateMessage_,
28 secret::SecretSingleton,
34 use lemmy_db_schema::{
39 local_user::{LocalUser, LocalUserForm},
41 password_reset_request::*,
43 person_block::{PersonBlock, PersonBlockForm},
46 private_message::PrivateMessage,
52 comment_report_view::CommentReportView,
53 comment_view::CommentQueryBuilder,
54 local_user_view::LocalUserView,
55 post_report_view::PostReportView,
57 use lemmy_db_views_actor::{
58 community_moderator_view::CommunityModeratorView,
59 person_mention_view::{PersonMentionQueryBuilder, PersonMentionView},
60 person_view::PersonViewSafe,
66 settings::structs::Settings,
67 utils::{generate_random_string, is_valid_display_name, is_valid_matrix_id, naive_from_unix},
72 use lemmy_websocket::{
73 messages::{CaptchaItem, SendAllMessage, SendUserRoomMessage},
78 #[async_trait::async_trait(?Send)]
79 impl Perform for Login {
80 type Response = LoginResponse;
84 context: &Data<LemmyContext>,
85 _websocket_id: Option<ConnectionId>,
86 ) -> Result<LoginResponse, LemmyError> {
87 let data: &Login = self;
89 // Fetch that username / email
90 let username_or_email = data.username_or_email.clone();
91 let local_user_view = blocking(context.pool(), move |conn| {
92 LocalUserView::find_by_email_or_name(conn, &username_or_email)
95 .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
97 // Verify the password
98 let valid: bool = verify(
100 &local_user_view.local_user.password_encrypted,
104 return Err(ApiError::err("password_incorrect").into());
108 let jwt_secret = Secret::get().jwt_secret;
110 jwt: Claims::jwt(local_user_view.local_user.id.0, &jwt_secret)?,
115 #[async_trait::async_trait(?Send)]
116 impl Perform for GetCaptcha {
117 type Response = GetCaptchaResponse;
121 context: &Data<LemmyContext>,
122 _websocket_id: Option<ConnectionId>,
123 ) -> Result<Self::Response, LemmyError> {
124 let captcha_settings = Settings::get().captcha;
126 if !captcha_settings.enabled {
127 return Ok(GetCaptchaResponse { ok: None });
130 let captcha = match captcha_settings.difficulty.as_str() {
131 "easy" => gen(Difficulty::Easy),
132 "medium" => gen(Difficulty::Medium),
133 "hard" => gen(Difficulty::Hard),
134 _ => gen(Difficulty::Medium),
137 let answer = captcha.chars_as_string();
139 let png = captcha.as_base64().expect("failed to generate captcha");
141 let uuid = uuid::Uuid::new_v4().to_string();
143 let wav = captcha_as_wav_base64(&captcha);
145 let captcha_item = CaptchaItem {
147 uuid: uuid.to_owned(),
148 expires: naive_now() + Duration::minutes(10), // expires in 10 minutes
151 // Stores the captcha item on the queue
152 context.chat_server().do_send(captcha_item);
154 Ok(GetCaptchaResponse {
155 ok: Some(CaptchaResponse { png, wav, uuid }),
160 #[async_trait::async_trait(?Send)]
161 impl Perform for SaveUserSettings {
162 type Response = LoginResponse;
166 context: &Data<LemmyContext>,
167 _websocket_id: Option<ConnectionId>,
168 ) -> Result<LoginResponse, LemmyError> {
169 let data: &SaveUserSettings = self;
170 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
172 let avatar = diesel_option_overwrite_to_url(&data.avatar)?;
173 let banner = diesel_option_overwrite_to_url(&data.banner)?;
174 let email = diesel_option_overwrite(&data.email);
175 let bio = diesel_option_overwrite(&data.bio);
176 let display_name = diesel_option_overwrite(&data.display_name);
177 let matrix_user_id = diesel_option_overwrite(&data.matrix_user_id);
178 let bot_account = data.bot_account;
180 if let Some(Some(bio)) = &bio {
181 if bio.chars().count() > 300 {
182 return Err(ApiError::err("bio_length_overflow").into());
186 if let Some(Some(display_name)) = &display_name {
187 if !is_valid_display_name(display_name.trim()) {
188 return Err(ApiError::err("invalid_username").into());
192 if let Some(Some(matrix_user_id)) = &matrix_user_id {
193 if !is_valid_matrix_id(matrix_user_id) {
194 return Err(ApiError::err("invalid_matrix_id").into());
198 let local_user_id = local_user_view.local_user.id;
199 let person_id = local_user_view.person.id;
200 let default_listing_type = data.default_listing_type;
201 let default_sort_type = data.default_sort_type;
202 let password_encrypted = local_user_view.local_user.password_encrypted;
204 let person_form = PersonForm {
205 name: local_user_view.person.name,
211 updated: Some(naive_now()),
220 last_refreshed_at: None,
221 shared_inbox_url: None,
226 let person_res = blocking(context.pool(), move |conn| {
227 Person::update(conn, person_id, &person_form)
230 let _updated_person: Person = match person_res {
233 return Err(ApiError::err("user_already_exists").into());
237 let local_user_form = LocalUserForm {
241 show_nsfw: data.show_nsfw,
242 show_bot_accounts: data.show_bot_accounts,
243 show_scores: data.show_scores,
244 theme: data.theme.to_owned(),
246 default_listing_type,
247 lang: data.lang.to_owned(),
248 show_avatars: data.show_avatars,
249 show_read_posts: data.show_read_posts,
250 show_new_post_notifs: data.show_new_post_notifs,
251 send_notifications_to_email: data.send_notifications_to_email,
254 let local_user_res = blocking(context.pool(), move |conn| {
255 LocalUser::update(conn, local_user_id, &local_user_form)
258 let updated_local_user = match local_user_res {
261 let err_type = if e.to_string()
262 == "duplicate key value violates unique constraint \"local_user_email_key\""
264 "email_already_exists"
266 "user_already_exists"
269 return Err(ApiError::err(err_type).into());
274 let jwt_secret = Secret::get().jwt_secret;
276 jwt: Claims::jwt(updated_local_user.id.0, &jwt_secret)?,
281 #[async_trait::async_trait(?Send)]
282 impl Perform for ChangePassword {
283 type Response = LoginResponse;
287 context: &Data<LemmyContext>,
288 _websocket_id: Option<ConnectionId>,
289 ) -> Result<LoginResponse, LemmyError> {
290 let data: &ChangePassword = self;
291 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
293 password_length_check(&data.new_password)?;
295 // Make sure passwords match
296 if data.new_password != data.new_password_verify {
297 return Err(ApiError::err("passwords_dont_match").into());
300 // Check the old password
301 let valid: bool = verify(
303 &local_user_view.local_user.password_encrypted,
307 return Err(ApiError::err("password_incorrect").into());
310 let local_user_id = local_user_view.local_user.id;
311 let new_password = data.new_password.to_owned();
312 let updated_local_user = blocking(context.pool(), move |conn| {
313 LocalUser::update_password(conn, local_user_id, &new_password)
318 let jwt_secret = Secret::get().jwt_secret;
320 jwt: Claims::jwt(updated_local_user.id.0, &jwt_secret)?,
325 #[async_trait::async_trait(?Send)]
326 impl Perform for AddAdmin {
327 type Response = AddAdminResponse;
331 context: &Data<LemmyContext>,
332 websocket_id: Option<ConnectionId>,
333 ) -> Result<AddAdminResponse, LemmyError> {
334 let data: &AddAdmin = self;
335 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
337 // Make sure user is an admin
338 is_admin(&local_user_view)?;
340 let added = data.added;
341 let added_person_id = data.person_id;
342 let added_admin = match blocking(context.pool(), move |conn| {
343 Person::add_admin(conn, added_person_id, added)
349 return Err(ApiError::err("couldnt_update_user").into());
354 let form = ModAddForm {
355 mod_person_id: local_user_view.person.id,
356 other_person_id: added_admin.id,
357 removed: Some(!data.added),
360 blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
362 let site_creator_id = blocking(context.pool(), move |conn| {
363 Site::read(conn, 1).map(|s| s.creator_id)
367 let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
368 let creator_index = admins
370 .position(|r| r.person.id == site_creator_id)
371 .context(location_info!())?;
372 let creator_person = admins.remove(creator_index);
373 admins.insert(0, creator_person);
375 let res = AddAdminResponse { admins };
377 context.chat_server().do_send(SendAllMessage {
378 op: UserOperation::AddAdmin,
379 response: res.clone(),
387 #[async_trait::async_trait(?Send)]
388 impl Perform for BanPerson {
389 type Response = BanPersonResponse;
393 context: &Data<LemmyContext>,
394 websocket_id: Option<ConnectionId>,
395 ) -> Result<BanPersonResponse, LemmyError> {
396 let data: &BanPerson = self;
397 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
399 // Make sure user is an admin
400 is_admin(&local_user_view)?;
403 let banned_person_id = data.person_id;
404 let ban_person = move |conn: &'_ _| Person::ban_person(conn, banned_person_id, ban);
405 if blocking(context.pool(), ban_person).await?.is_err() {
406 return Err(ApiError::err("couldnt_update_user").into());
409 // Remove their data if that's desired
410 if data.remove_data.unwrap_or(false) {
412 blocking(context.pool(), move |conn: &'_ _| {
413 Post::update_removed_for_creator(conn, banned_person_id, None, true)
418 // Remove all communities where they're the top mod
419 // for now, remove the communities manually
420 let first_mod_communities = blocking(context.pool(), move |conn: &'_ _| {
421 CommunityModeratorView::get_community_first_mods(conn)
425 // Filter to only this banned users top communities
426 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
428 .filter(|fmc| fmc.moderator.id == banned_person_id)
431 for first_mod_community in banned_user_first_communities {
432 blocking(context.pool(), move |conn: &'_ _| {
433 Community::update_removed(conn, first_mod_community.community.id, true)
439 blocking(context.pool(), move |conn: &'_ _| {
440 Comment::update_removed_for_creator(conn, banned_person_id, true)
446 let expires = data.expires.map(naive_from_unix);
448 let form = ModBanForm {
449 mod_person_id: local_user_view.person.id,
450 other_person_id: data.person_id,
451 reason: data.reason.to_owned(),
452 banned: Some(data.ban),
456 blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??;
458 let person_id = data.person_id;
459 let person_view = blocking(context.pool(), move |conn| {
460 PersonViewSafe::read(conn, person_id)
464 let res = BanPersonResponse {
469 context.chat_server().do_send(SendAllMessage {
470 op: UserOperation::BanPerson,
471 response: res.clone(),
479 #[async_trait::async_trait(?Send)]
480 impl Perform for BlockPerson {
481 type Response = BlockPersonResponse;
485 context: &Data<LemmyContext>,
486 _websocket_id: Option<ConnectionId>,
487 ) -> Result<BlockPersonResponse, LemmyError> {
488 let data: &BlockPerson = self;
489 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
491 let target_id = data.person_id;
492 let person_id = local_user_view.person.id;
494 // Don't let a person block themselves
495 if target_id == person_id {
496 return Err(ApiError::err("cant_block_yourself").into());
499 let person_block_form = PersonBlockForm {
505 let block = move |conn: &'_ _| PersonBlock::block(conn, &person_block_form);
506 if blocking(context.pool(), block).await?.is_err() {
507 return Err(ApiError::err("person_block_already_exists").into());
510 let unblock = move |conn: &'_ _| PersonBlock::unblock(conn, &person_block_form);
511 if blocking(context.pool(), unblock).await?.is_err() {
512 return Err(ApiError::err("person_block_already_exists").into());
516 // TODO does any federated stuff need to be done here?
518 let person_view = blocking(context.pool(), move |conn| {
519 PersonViewSafe::read(conn, target_id)
523 let res = BlockPersonResponse {
532 #[async_trait::async_trait(?Send)]
533 impl Perform for GetReplies {
534 type Response = GetRepliesResponse;
538 context: &Data<LemmyContext>,
539 _websocket_id: Option<ConnectionId>,
540 ) -> Result<GetRepliesResponse, LemmyError> {
541 let data: &GetReplies = self;
542 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
544 let sort: Option<SortType> = from_opt_str_to_opt_enum(&data.sort);
546 let page = data.page;
547 let limit = data.limit;
548 let unread_only = data.unread_only;
549 let person_id = local_user_view.person.id;
550 let show_bot_accounts = local_user_view.local_user.show_bot_accounts;
552 let replies = blocking(context.pool(), move |conn| {
553 CommentQueryBuilder::create(conn)
555 .unread_only(unread_only)
556 .recipient_id(person_id)
557 .show_bot_accounts(show_bot_accounts)
558 .my_person_id(person_id)
565 Ok(GetRepliesResponse { replies })
569 #[async_trait::async_trait(?Send)]
570 impl Perform for GetPersonMentions {
571 type Response = GetPersonMentionsResponse;
575 context: &Data<LemmyContext>,
576 _websocket_id: Option<ConnectionId>,
577 ) -> Result<GetPersonMentionsResponse, LemmyError> {
578 let data: &GetPersonMentions = self;
579 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
581 let sort: Option<SortType> = from_opt_str_to_opt_enum(&data.sort);
583 let page = data.page;
584 let limit = data.limit;
585 let unread_only = data.unread_only;
586 let person_id = local_user_view.person.id;
587 let mentions = blocking(context.pool(), move |conn| {
588 PersonMentionQueryBuilder::create(conn)
589 .recipient_id(person_id)
590 .my_person_id(person_id)
592 .unread_only(unread_only)
599 Ok(GetPersonMentionsResponse { mentions })
603 #[async_trait::async_trait(?Send)]
604 impl Perform for MarkPersonMentionAsRead {
605 type Response = PersonMentionResponse;
609 context: &Data<LemmyContext>,
610 _websocket_id: Option<ConnectionId>,
611 ) -> Result<PersonMentionResponse, LemmyError> {
612 let data: &MarkPersonMentionAsRead = self;
613 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
615 let person_mention_id = data.person_mention_id;
616 let read_person_mention = blocking(context.pool(), move |conn| {
617 PersonMention::read(conn, person_mention_id)
621 if local_user_view.person.id != read_person_mention.recipient_id {
622 return Err(ApiError::err("couldnt_update_comment").into());
625 let person_mention_id = read_person_mention.id;
626 let read = data.read;
628 move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read);
629 if blocking(context.pool(), update_mention).await?.is_err() {
630 return Err(ApiError::err("couldnt_update_comment").into());
633 let person_mention_id = read_person_mention.id;
634 let person_id = local_user_view.person.id;
635 let person_mention_view = blocking(context.pool(), move |conn| {
636 PersonMentionView::read(conn, person_mention_id, Some(person_id))
640 Ok(PersonMentionResponse {
646 #[async_trait::async_trait(?Send)]
647 impl Perform for MarkAllAsRead {
648 type Response = GetRepliesResponse;
652 context: &Data<LemmyContext>,
653 _websocket_id: Option<ConnectionId>,
654 ) -> Result<GetRepliesResponse, LemmyError> {
655 let data: &MarkAllAsRead = self;
656 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
658 let person_id = local_user_view.person.id;
659 let replies = blocking(context.pool(), move |conn| {
660 CommentQueryBuilder::create(conn)
661 .my_person_id(person_id)
662 .recipient_id(person_id)
670 // TODO: this should probably be a bulk operation
671 // Not easy to do as a bulk operation,
672 // because recipient_id isn't in the comment table
673 for comment_view in &replies {
674 let reply_id = comment_view.comment.id;
675 let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true);
676 if blocking(context.pool(), mark_as_read).await?.is_err() {
677 return Err(ApiError::err("couldnt_update_comment").into());
681 // Mark all user mentions as read
682 let update_person_mentions =
683 move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id);
684 if blocking(context.pool(), update_person_mentions)
688 return Err(ApiError::err("couldnt_update_comment").into());
691 // Mark all private_messages as read
692 let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id);
693 if blocking(context.pool(), update_pm).await?.is_err() {
694 return Err(ApiError::err("couldnt_update_private_message").into());
697 Ok(GetRepliesResponse { replies: vec![] })
701 #[async_trait::async_trait(?Send)]
702 impl Perform for PasswordReset {
703 type Response = PasswordResetResponse;
707 context: &Data<LemmyContext>,
708 _websocket_id: Option<ConnectionId>,
709 ) -> Result<PasswordResetResponse, LemmyError> {
710 let data: &PasswordReset = self;
713 let email = data.email.clone();
714 let local_user_view = blocking(context.pool(), move |conn| {
715 LocalUserView::find_by_email(conn, &email)
718 .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
720 // Generate a random token
721 let token = generate_random_string();
724 let token2 = token.clone();
725 let local_user_id = local_user_view.local_user.id;
726 blocking(context.pool(), move |conn| {
727 PasswordResetRequest::create_token(conn, local_user_id, &token2)
731 // Email the pure token to the user.
732 // TODO no i18n support here.
733 let email = &local_user_view.local_user.email.expect("email");
734 let subject = &format!("Password reset for {}", local_user_view.person.name);
735 let hostname = &Settings::get().get_protocol_and_hostname();
736 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, hostname, &token);
737 send_email(subject, email, &local_user_view.person.name, html)
738 .map_err(|e| ApiError::err(&e))?;
740 Ok(PasswordResetResponse {})
744 #[async_trait::async_trait(?Send)]
745 impl Perform for PasswordChange {
746 type Response = LoginResponse;
750 context: &Data<LemmyContext>,
751 _websocket_id: Option<ConnectionId>,
752 ) -> Result<LoginResponse, LemmyError> {
753 let data: &PasswordChange = self;
755 // Fetch the user_id from the token
756 let token = data.token.clone();
757 let local_user_id = blocking(context.pool(), move |conn| {
758 PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id)
762 password_length_check(&data.password)?;
764 // Make sure passwords match
765 if data.password != data.password_verify {
766 return Err(ApiError::err("passwords_dont_match").into());
769 // Update the user with the new password
770 let password = data.password.clone();
771 let updated_local_user = blocking(context.pool(), move |conn| {
772 LocalUser::update_password(conn, local_user_id, &password)
775 .map_err(|_| ApiError::err("couldnt_update_user"))?;
778 let jwt_secret = Secret::get().jwt_secret;
780 jwt: Claims::jwt(updated_local_user.id.0, &jwt_secret)?,
785 #[async_trait::async_trait(?Send)]
786 impl Perform for GetReportCount {
787 type Response = GetReportCountResponse;
791 context: &Data<LemmyContext>,
792 websocket_id: Option<ConnectionId>,
793 ) -> Result<GetReportCountResponse, LemmyError> {
794 let data: &GetReportCount = self;
795 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
797 let person_id = local_user_view.person.id;
798 let community_id = data.community;
800 collect_moderated_communities(person_id, community_id, context.pool()).await?;
803 if community_ids.is_empty() {
804 GetReportCountResponse {
810 let ids = community_ids.clone();
811 let comment_reports = blocking(context.pool(), move |conn| {
812 CommentReportView::get_report_count(conn, &ids)
816 let ids = community_ids.clone();
817 let post_reports = blocking(context.pool(), move |conn| {
818 PostReportView::get_report_count(conn, &ids)
822 GetReportCountResponse {
823 community: data.community,
830 context.chat_server().do_send(SendUserRoomMessage {
831 op: UserOperation::GetReportCount,
832 response: res.clone(),
833 local_recipient_id: local_user_view.local_user.id,