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 get_local_user_view_from_jwt,
11 password_length_check,
14 use lemmy_db_queries::{
15 diesel_option_overwrite,
16 diesel_option_overwrite_to_url,
17 from_opt_str_to_opt_enum,
20 community::Community_,
21 local_user::LocalUser_,
22 password_reset_request::PasswordResetRequest_,
24 person_mention::PersonMention_,
26 private_message::PrivateMessage_,
32 use lemmy_db_schema::{
37 local_user::{LocalUser, LocalUserForm},
39 password_reset_request::*,
41 person_block::{PersonBlock, PersonBlockForm},
44 private_message::PrivateMessage,
49 comment_report_view::CommentReportView,
50 comment_view::CommentQueryBuilder,
51 local_user_view::LocalUserView,
52 post_report_view::PostReportView,
54 use lemmy_db_views_actor::{
55 community_moderator_view::CommunityModeratorView,
56 person_mention_view::{PersonMentionQueryBuilder, PersonMentionView},
57 person_view::PersonViewSafe,
63 utils::{generate_random_string, is_valid_display_name, is_valid_matrix_id, naive_from_unix},
68 use lemmy_websocket::{
69 messages::{CaptchaItem, SendAllMessage},
74 #[async_trait::async_trait(?Send)]
75 impl Perform for Login {
76 type Response = LoginResponse;
80 context: &Data<LemmyContext>,
81 _websocket_id: Option<ConnectionId>,
82 ) -> Result<LoginResponse, LemmyError> {
83 let data: &Login = self;
85 // Fetch that username / email
86 let username_or_email = data.username_or_email.clone();
87 let local_user_view = blocking(context.pool(), move |conn| {
88 LocalUserView::find_by_email_or_name(conn, &username_or_email)
91 .map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?;
93 // Verify the password
94 let valid: bool = verify(
96 &local_user_view.local_user.password_encrypted,
100 return Err(ApiError::err_plain("password_incorrect").into());
106 local_user_view.local_user.id.0,
107 &context.secret().jwt_secret,
108 &context.settings().hostname,
114 #[async_trait::async_trait(?Send)]
115 impl Perform for GetCaptcha {
116 type Response = GetCaptchaResponse;
120 context: &Data<LemmyContext>,
121 _websocket_id: Option<ConnectionId>,
122 ) -> Result<Self::Response, LemmyError> {
123 let captcha_settings = context.settings().captcha;
125 if !captcha_settings.enabled {
126 return Ok(GetCaptchaResponse { ok: None });
129 let captcha = match captcha_settings.difficulty.as_str() {
130 "easy" => gen(Difficulty::Easy),
131 "medium" => gen(Difficulty::Medium),
132 "hard" => gen(Difficulty::Hard),
133 _ => gen(Difficulty::Medium),
136 let answer = captcha.chars_as_string();
138 let png = captcha.as_base64().expect("failed to generate captcha");
140 let uuid = uuid::Uuid::new_v4().to_string();
142 let wav = captcha_as_wav_base64(&captcha);
144 let captcha_item = CaptchaItem {
146 uuid: uuid.to_owned(),
147 expires: naive_now() + Duration::minutes(10), // expires in 10 minutes
150 // Stores the captcha item on the queue
151 context.chat_server().do_send(captcha_item);
153 Ok(GetCaptchaResponse {
154 ok: Some(CaptchaResponse { png, wav, uuid }),
159 #[async_trait::async_trait(?Send)]
160 impl Perform for SaveUserSettings {
161 type Response = LoginResponse;
165 context: &Data<LemmyContext>,
166 _websocket_id: Option<ConnectionId>,
167 ) -> Result<LoginResponse, LemmyError> {
168 let data: &SaveUserSettings = self;
169 let local_user_view =
170 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).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_plain("bio_length_overflow").into());
186 if let Some(Some(display_name)) = &display_name {
187 if !is_valid_display_name(
189 context.settings().actor_name_max_length,
191 return Err(ApiError::err_plain("invalid_username").into());
195 if let Some(Some(matrix_user_id)) = &matrix_user_id {
196 if !is_valid_matrix_id(matrix_user_id) {
197 return Err(ApiError::err_plain("invalid_matrix_id").into());
201 let local_user_id = local_user_view.local_user.id;
202 let person_id = local_user_view.person.id;
203 let default_listing_type = data.default_listing_type;
204 let default_sort_type = data.default_sort_type;
205 let password_encrypted = local_user_view.local_user.password_encrypted;
207 let person_form = PersonForm {
208 name: local_user_view.person.name,
214 updated: Some(naive_now()),
223 last_refreshed_at: None,
224 shared_inbox_url: None,
229 blocking(context.pool(), move |conn| {
230 Person::update(conn, person_id, &person_form)
233 .map_err(|e| ApiError::err("user_already_exists", e))?;
235 let local_user_form = LocalUserForm {
239 show_nsfw: data.show_nsfw,
240 show_bot_accounts: data.show_bot_accounts,
241 show_scores: data.show_scores,
242 theme: data.theme.to_owned(),
244 default_listing_type,
245 lang: data.lang.to_owned(),
246 show_avatars: data.show_avatars,
247 show_read_posts: data.show_read_posts,
248 show_new_post_notifs: data.show_new_post_notifs,
249 send_notifications_to_email: data.send_notifications_to_email,
252 let local_user_res = blocking(context.pool(), move |conn| {
253 LocalUser::update(conn, local_user_id, &local_user_form)
256 let updated_local_user = match local_user_res {
259 let err_type = if e.to_string()
260 == "duplicate key value violates unique constraint \"local_user_email_key\""
262 "email_already_exists"
264 "user_already_exists"
267 return Err(ApiError::err(err_type, e).into());
274 updated_local_user.id.0,
275 &context.secret().jwt_secret,
276 &context.settings().hostname,
282 #[async_trait::async_trait(?Send)]
283 impl Perform for ChangePassword {
284 type Response = LoginResponse;
288 context: &Data<LemmyContext>,
289 _websocket_id: Option<ConnectionId>,
290 ) -> Result<LoginResponse, LemmyError> {
291 let data: &ChangePassword = self;
292 let local_user_view =
293 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
295 password_length_check(&data.new_password)?;
297 // Make sure passwords match
298 if data.new_password != data.new_password_verify {
299 return Err(ApiError::err_plain("passwords_dont_match").into());
302 // Check the old password
303 let valid: bool = verify(
305 &local_user_view.local_user.password_encrypted,
309 return Err(ApiError::err_plain("password_incorrect").into());
312 let local_user_id = local_user_view.local_user.id;
313 let new_password = data.new_password.to_owned();
314 let updated_local_user = blocking(context.pool(), move |conn| {
315 LocalUser::update_password(conn, local_user_id, &new_password)
322 updated_local_user.id.0,
323 &context.secret().jwt_secret,
324 &context.settings().hostname,
330 #[async_trait::async_trait(?Send)]
331 impl Perform for AddAdmin {
332 type Response = AddAdminResponse;
336 context: &Data<LemmyContext>,
337 websocket_id: Option<ConnectionId>,
338 ) -> Result<AddAdminResponse, LemmyError> {
339 let data: &AddAdmin = self;
340 let local_user_view =
341 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
343 // Make sure user is an admin
344 is_admin(&local_user_view)?;
346 let added = data.added;
347 let added_person_id = data.person_id;
348 let added_admin = blocking(context.pool(), move |conn| {
349 Person::add_admin(conn, added_person_id, added)
352 .map_err(|e| ApiError::err("couldnt_update_user", e))?;
355 let form = ModAddForm {
356 mod_person_id: local_user_view.person.id,
357 other_person_id: added_admin.id,
358 removed: Some(!data.added),
361 blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
363 let site_creator_id = blocking(context.pool(), move |conn| {
364 Site::read(conn, 1).map(|s| s.creator_id)
368 let mut admins = blocking(context.pool(), PersonViewSafe::admins).await??;
369 let creator_index = admins
371 .position(|r| r.person.id == site_creator_id)
372 .context(location_info!())?;
373 let creator_person = admins.remove(creator_index);
374 admins.insert(0, creator_person);
376 let res = AddAdminResponse { admins };
378 context.chat_server().do_send(SendAllMessage {
379 op: UserOperation::AddAdmin,
380 response: res.clone(),
388 #[async_trait::async_trait(?Send)]
389 impl Perform for BanPerson {
390 type Response = BanPersonResponse;
394 context: &Data<LemmyContext>,
395 websocket_id: Option<ConnectionId>,
396 ) -> Result<BanPersonResponse, LemmyError> {
397 let data: &BanPerson = self;
398 let local_user_view =
399 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
401 // Make sure user is an admin
402 is_admin(&local_user_view)?;
405 let banned_person_id = data.person_id;
406 let ban_person = move |conn: &'_ _| Person::ban_person(conn, banned_person_id, ban);
407 blocking(context.pool(), ban_person)
409 .map_err(|e| ApiError::err("couldnt_update_user", e))?;
411 // Remove their data if that's desired
412 if data.remove_data.unwrap_or(false) {
414 blocking(context.pool(), move |conn: &'_ _| {
415 Post::update_removed_for_creator(conn, banned_person_id, None, true)
420 // Remove all communities where they're the top mod
421 // for now, remove the communities manually
422 let first_mod_communities = blocking(context.pool(), move |conn: &'_ _| {
423 CommunityModeratorView::get_community_first_mods(conn)
427 // Filter to only this banned users top communities
428 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
430 .filter(|fmc| fmc.moderator.id == banned_person_id)
433 for first_mod_community in banned_user_first_communities {
434 blocking(context.pool(), move |conn: &'_ _| {
435 Community::update_removed(conn, first_mod_community.community.id, true)
441 blocking(context.pool(), move |conn: &'_ _| {
442 Comment::update_removed_for_creator(conn, banned_person_id, true)
448 let expires = data.expires.map(naive_from_unix);
450 let form = ModBanForm {
451 mod_person_id: local_user_view.person.id,
452 other_person_id: data.person_id,
453 reason: data.reason.to_owned(),
454 banned: Some(data.ban),
458 blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??;
460 let person_id = data.person_id;
461 let person_view = blocking(context.pool(), move |conn| {
462 PersonViewSafe::read(conn, person_id)
466 let res = BanPersonResponse {
471 context.chat_server().do_send(SendAllMessage {
472 op: UserOperation::BanPerson,
473 response: res.clone(),
481 #[async_trait::async_trait(?Send)]
482 impl Perform for BlockPerson {
483 type Response = BlockPersonResponse;
487 context: &Data<LemmyContext>,
488 _websocket_id: Option<ConnectionId>,
489 ) -> Result<BlockPersonResponse, LemmyError> {
490 let data: &BlockPerson = self;
491 let local_user_view =
492 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
494 let target_id = data.person_id;
495 let person_id = local_user_view.person.id;
497 // Don't let a person block themselves
498 if target_id == person_id {
499 return Err(ApiError::err_plain("cant_block_yourself").into());
502 let person_block_form = PersonBlockForm {
508 let block = move |conn: &'_ _| PersonBlock::block(conn, &person_block_form);
509 blocking(context.pool(), block)
511 .map_err(|e| ApiError::err("person_block_already_exists", e))?;
513 let unblock = move |conn: &'_ _| PersonBlock::unblock(conn, &person_block_form);
514 blocking(context.pool(), unblock)
516 .map_err(|e| ApiError::err("person_block_already_exists", e))?;
519 // TODO does any federated stuff need to be done here?
521 let person_view = blocking(context.pool(), move |conn| {
522 PersonViewSafe::read(conn, target_id)
526 let res = BlockPersonResponse {
535 #[async_trait::async_trait(?Send)]
536 impl Perform for GetReplies {
537 type Response = GetRepliesResponse;
541 context: &Data<LemmyContext>,
542 _websocket_id: Option<ConnectionId>,
543 ) -> Result<GetRepliesResponse, LemmyError> {
544 let data: &GetReplies = self;
545 let local_user_view =
546 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
548 let sort: Option<SortType> = from_opt_str_to_opt_enum(&data.sort);
550 let page = data.page;
551 let limit = data.limit;
552 let unread_only = data.unread_only;
553 let person_id = local_user_view.person.id;
554 let show_bot_accounts = local_user_view.local_user.show_bot_accounts;
556 let replies = blocking(context.pool(), move |conn| {
557 CommentQueryBuilder::create(conn)
559 .unread_only(unread_only)
560 .recipient_id(person_id)
561 .show_bot_accounts(show_bot_accounts)
562 .my_person_id(person_id)
569 Ok(GetRepliesResponse { replies })
573 #[async_trait::async_trait(?Send)]
574 impl Perform for GetPersonMentions {
575 type Response = GetPersonMentionsResponse;
579 context: &Data<LemmyContext>,
580 _websocket_id: Option<ConnectionId>,
581 ) -> Result<GetPersonMentionsResponse, LemmyError> {
582 let data: &GetPersonMentions = self;
583 let local_user_view =
584 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
586 let sort: Option<SortType> = from_opt_str_to_opt_enum(&data.sort);
588 let page = data.page;
589 let limit = data.limit;
590 let unread_only = data.unread_only;
591 let person_id = local_user_view.person.id;
592 let mentions = blocking(context.pool(), move |conn| {
593 PersonMentionQueryBuilder::create(conn)
594 .recipient_id(person_id)
595 .my_person_id(person_id)
597 .unread_only(unread_only)
604 Ok(GetPersonMentionsResponse { mentions })
608 #[async_trait::async_trait(?Send)]
609 impl Perform for MarkPersonMentionAsRead {
610 type Response = PersonMentionResponse;
614 context: &Data<LemmyContext>,
615 _websocket_id: Option<ConnectionId>,
616 ) -> Result<PersonMentionResponse, LemmyError> {
617 let data: &MarkPersonMentionAsRead = self;
618 let local_user_view =
619 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
621 let person_mention_id = data.person_mention_id;
622 let read_person_mention = blocking(context.pool(), move |conn| {
623 PersonMention::read(conn, person_mention_id)
627 if local_user_view.person.id != read_person_mention.recipient_id {
628 return Err(ApiError::err_plain("couldnt_update_comment").into());
631 let person_mention_id = read_person_mention.id;
632 let read = data.read;
634 move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read);
635 blocking(context.pool(), update_mention)
637 .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
639 let person_mention_id = read_person_mention.id;
640 let person_id = local_user_view.person.id;
641 let person_mention_view = blocking(context.pool(), move |conn| {
642 PersonMentionView::read(conn, person_mention_id, Some(person_id))
646 Ok(PersonMentionResponse {
652 #[async_trait::async_trait(?Send)]
653 impl Perform for MarkAllAsRead {
654 type Response = GetRepliesResponse;
658 context: &Data<LemmyContext>,
659 _websocket_id: Option<ConnectionId>,
660 ) -> Result<GetRepliesResponse, LemmyError> {
661 let data: &MarkAllAsRead = self;
662 let local_user_view =
663 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
665 let person_id = local_user_view.person.id;
666 let replies = blocking(context.pool(), move |conn| {
667 CommentQueryBuilder::create(conn)
668 .my_person_id(person_id)
669 .recipient_id(person_id)
677 // TODO: this should probably be a bulk operation
678 // Not easy to do as a bulk operation,
679 // because recipient_id isn't in the comment table
680 for comment_view in &replies {
681 let reply_id = comment_view.comment.id;
682 let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true);
683 blocking(context.pool(), mark_as_read)
685 .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
688 // Mark all user mentions as read
689 let update_person_mentions =
690 move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id);
691 blocking(context.pool(), update_person_mentions)
693 .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
695 // Mark all private_messages as read
696 let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id);
697 blocking(context.pool(), update_pm)
699 .map_err(|e| ApiError::err("couldnt_update_private_message", e))?;
701 Ok(GetRepliesResponse { replies: vec![] })
705 #[async_trait::async_trait(?Send)]
706 impl Perform for PasswordReset {
707 type Response = PasswordResetResponse;
711 context: &Data<LemmyContext>,
712 _websocket_id: Option<ConnectionId>,
713 ) -> Result<PasswordResetResponse, LemmyError> {
714 let data: &PasswordReset = self;
717 let email = data.email.clone();
718 let local_user_view = blocking(context.pool(), move |conn| {
719 LocalUserView::find_by_email(conn, &email)
722 .map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?;
724 // Generate a random token
725 let token = generate_random_string();
728 let token2 = token.clone();
729 let local_user_id = local_user_view.local_user.id;
730 blocking(context.pool(), move |conn| {
731 PasswordResetRequest::create_token(conn, local_user_id, &token2)
735 // Email the pure token to the user.
736 // TODO no i18n support here.
737 let email = &local_user_view.local_user.email.expect("email");
738 let subject = &format!("Password reset for {}", local_user_view.person.name);
739 let protocol_and_hostname = &context.settings().get_protocol_and_hostname();
740 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);
744 &local_user_view.person.name,
748 .map_err(|e| ApiError::err("email_send_failed", e))?;
750 Ok(PasswordResetResponse {})
754 #[async_trait::async_trait(?Send)]
755 impl Perform for PasswordChange {
756 type Response = LoginResponse;
760 context: &Data<LemmyContext>,
761 _websocket_id: Option<ConnectionId>,
762 ) -> Result<LoginResponse, LemmyError> {
763 let data: &PasswordChange = self;
765 // Fetch the user_id from the token
766 let token = data.token.clone();
767 let local_user_id = blocking(context.pool(), move |conn| {
768 PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id)
772 password_length_check(&data.password)?;
774 // Make sure passwords match
775 if data.password != data.password_verify {
776 return Err(ApiError::err_plain("passwords_dont_match").into());
779 // Update the user with the new password
780 let password = data.password.clone();
781 let updated_local_user = blocking(context.pool(), move |conn| {
782 LocalUser::update_password(conn, local_user_id, &password)
785 .map_err(|e| ApiError::err("couldnt_update_user", e))?;
790 updated_local_user.id.0,
791 &context.secret().jwt_secret,
792 &context.settings().hostname,
798 #[async_trait::async_trait(?Send)]
799 impl Perform for GetReportCount {
800 type Response = GetReportCountResponse;
804 context: &Data<LemmyContext>,
805 _websocket_id: Option<ConnectionId>,
806 ) -> Result<GetReportCountResponse, LemmyError> {
807 let data: &GetReportCount = self;
808 let local_user_view =
809 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
811 let person_id = local_user_view.person.id;
812 let admin = local_user_view.person.admin;
813 let community_id = data.community_id;
815 let comment_reports = blocking(context.pool(), move |conn| {
816 CommentReportView::get_report_count(conn, person_id, admin, community_id)
820 let post_reports = blocking(context.pool(), move |conn| {
821 PostReportView::get_report_count(conn, person_id, admin, community_id)
825 let res = GetReportCountResponse {