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 community::{GetFollowedCommunities, GetFollowedCommunitiesResponse},
11 get_local_user_view_from_jwt,
13 password_length_check,
16 use lemmy_db_queries::{
17 diesel_option_overwrite,
18 diesel_option_overwrite_to_url,
19 from_opt_str_to_opt_enum,
22 community::Community_,
23 local_user::LocalUser_,
24 password_reset_request::PasswordResetRequest_,
26 person_mention::PersonMention_,
28 private_message::PrivateMessage_,
33 use lemmy_db_schema::{
38 local_user::{LocalUser, LocalUserForm},
40 password_reset_request::*,
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_follower_view::CommunityFollowerView,
56 community_moderator_view::CommunityModeratorView,
57 person_mention_view::{PersonMentionQueryBuilder, PersonMentionView},
58 person_view::PersonViewSafe,
64 settings::structs::Settings,
65 utils::{generate_random_string, is_valid_display_name, is_valid_matrix_id, naive_from_unix},
70 use lemmy_websocket::{
71 messages::{CaptchaItem, SendAllMessage, SendUserRoomMessage},
76 #[async_trait::async_trait(?Send)]
77 impl Perform for Login {
78 type Response = LoginResponse;
82 context: &Data<LemmyContext>,
83 _websocket_id: Option<ConnectionId>,
84 ) -> Result<LoginResponse, LemmyError> {
85 let data: &Login = self;
87 // Fetch that username / email
88 let username_or_email = data.username_or_email.clone();
89 let local_user_view = blocking(context.pool(), move |conn| {
90 LocalUserView::find_by_email_or_name(conn, &username_or_email)
93 .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
95 // Verify the password
96 let valid: bool = verify(
98 &local_user_view.local_user.password_encrypted,
102 return Err(ApiError::err("password_incorrect").into());
107 jwt: Claims::jwt(local_user_view.local_user.id.0)?,
112 #[async_trait::async_trait(?Send)]
113 impl Perform for GetCaptcha {
114 type Response = GetCaptchaResponse;
118 context: &Data<LemmyContext>,
119 _websocket_id: Option<ConnectionId>,
120 ) -> Result<Self::Response, LemmyError> {
121 let captcha_settings = Settings::get().captcha;
123 if !captcha_settings.enabled {
124 return Ok(GetCaptchaResponse { ok: None });
127 let captcha = match captcha_settings.difficulty.as_str() {
128 "easy" => gen(Difficulty::Easy),
129 "medium" => gen(Difficulty::Medium),
130 "hard" => gen(Difficulty::Hard),
131 _ => gen(Difficulty::Medium),
134 let answer = captcha.chars_as_string();
136 let png = captcha.as_base64().expect("failed to generate captcha");
138 let uuid = uuid::Uuid::new_v4().to_string();
140 let wav = captcha_as_wav_base64(&captcha);
142 let captcha_item = CaptchaItem {
144 uuid: uuid.to_owned(),
145 expires: naive_now() + Duration::minutes(10), // expires in 10 minutes
148 // Stores the captcha item on the queue
149 context.chat_server().do_send(captcha_item);
151 Ok(GetCaptchaResponse {
152 ok: Some(CaptchaResponse { png, wav, uuid }),
157 #[async_trait::async_trait(?Send)]
158 impl Perform for SaveUserSettings {
159 type Response = LoginResponse;
163 context: &Data<LemmyContext>,
164 _websocket_id: Option<ConnectionId>,
165 ) -> Result<LoginResponse, LemmyError> {
166 let data: &SaveUserSettings = self;
167 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
169 let avatar = diesel_option_overwrite_to_url(&data.avatar)?;
170 let banner = diesel_option_overwrite_to_url(&data.banner)?;
171 let email = diesel_option_overwrite(&data.email);
172 let bio = diesel_option_overwrite(&data.bio);
173 let display_name = diesel_option_overwrite(&data.display_name);
174 let matrix_user_id = diesel_option_overwrite(&data.matrix_user_id);
175 let bot_account = data.bot_account;
177 if let Some(Some(bio)) = &bio {
178 if bio.chars().count() > 300 {
179 return Err(ApiError::err("bio_length_overflow").into());
183 if let Some(Some(display_name)) = &display_name {
184 if !is_valid_display_name(display_name.trim()) {
185 return Err(ApiError::err("invalid_username").into());
189 if let Some(Some(matrix_user_id)) = &matrix_user_id {
190 if !is_valid_matrix_id(matrix_user_id) {
191 return Err(ApiError::err("invalid_matrix_id").into());
195 let local_user_id = local_user_view.local_user.id;
196 let person_id = local_user_view.person.id;
197 let default_listing_type = data.default_listing_type;
198 let default_sort_type = data.default_sort_type;
199 let password_encrypted = local_user_view.local_user.password_encrypted;
201 let person_form = PersonForm {
202 name: local_user_view.person.name,
208 updated: Some(naive_now()),
217 last_refreshed_at: None,
218 shared_inbox_url: None,
223 let person_res = blocking(context.pool(), move |conn| {
224 Person::update(conn, person_id, &person_form)
227 let _updated_person: Person = match person_res {
230 return Err(ApiError::err("user_already_exists").into());
234 let local_user_form = LocalUserForm {
238 show_nsfw: data.show_nsfw,
239 show_bot_accounts: data.show_bot_accounts,
240 show_scores: data.show_scores,
241 theme: data.theme.to_owned(),
243 default_listing_type,
244 lang: data.lang.to_owned(),
245 show_avatars: data.show_avatars,
246 show_read_posts: data.show_read_posts,
247 show_new_post_notifs: data.show_new_post_notifs,
248 send_notifications_to_email: data.send_notifications_to_email,
251 let local_user_res = blocking(context.pool(), move |conn| {
252 LocalUser::update(conn, local_user_id, &local_user_form)
255 let updated_local_user = match local_user_res {
258 let err_type = if e.to_string()
259 == "duplicate key value violates unique constraint \"local_user_email_key\""
261 "email_already_exists"
263 "user_already_exists"
266 return Err(ApiError::err(err_type).into());
272 jwt: Claims::jwt(updated_local_user.id.0)?,
277 #[async_trait::async_trait(?Send)]
278 impl Perform for ChangePassword {
279 type Response = LoginResponse;
283 context: &Data<LemmyContext>,
284 _websocket_id: Option<ConnectionId>,
285 ) -> Result<LoginResponse, LemmyError> {
286 let data: &ChangePassword = self;
287 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
289 password_length_check(&data.new_password)?;
291 // Make sure passwords match
292 if data.new_password != data.new_password_verify {
293 return Err(ApiError::err("passwords_dont_match").into());
296 // Check the old password
297 let valid: bool = verify(
299 &local_user_view.local_user.password_encrypted,
303 return Err(ApiError::err("password_incorrect").into());
306 let local_user_id = local_user_view.local_user.id;
307 let new_password = data.new_password.to_owned();
308 let updated_local_user = blocking(context.pool(), move |conn| {
309 LocalUser::update_password(conn, local_user_id, &new_password)
315 jwt: Claims::jwt(updated_local_user.id.0)?,
320 #[async_trait::async_trait(?Send)]
321 impl Perform for AddAdmin {
322 type Response = AddAdminResponse;
326 context: &Data<LemmyContext>,
327 websocket_id: Option<ConnectionId>,
328 ) -> Result<AddAdminResponse, LemmyError> {
329 let data: &AddAdmin = self;
330 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
332 // Make sure user is an admin
333 is_admin(&local_user_view)?;
335 let added = data.added;
336 let added_person_id = data.person_id;
337 let added_admin = match blocking(context.pool(), move |conn| {
338 Person::add_admin(conn, added_person_id, added)
344 return Err(ApiError::err("couldnt_update_user").into());
349 let form = ModAddForm {
350 mod_person_id: local_user_view.person.id,
351 other_person_id: added_admin.id,
352 removed: Some(!data.added),
355 blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
357 let site_creator_id = blocking(context.pool(), move |conn| {
358 Site::read(conn, 1).map(|s| s.creator_id)
362 let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
363 let creator_index = admins
365 .position(|r| r.person.id == site_creator_id)
366 .context(location_info!())?;
367 let creator_person = admins.remove(creator_index);
368 admins.insert(0, creator_person);
370 let res = AddAdminResponse { admins };
372 context.chat_server().do_send(SendAllMessage {
373 op: UserOperation::AddAdmin,
374 response: res.clone(),
382 #[async_trait::async_trait(?Send)]
383 impl Perform for BanPerson {
384 type Response = BanPersonResponse;
388 context: &Data<LemmyContext>,
389 websocket_id: Option<ConnectionId>,
390 ) -> Result<BanPersonResponse, LemmyError> {
391 let data: &BanPerson = self;
392 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
394 // Make sure user is an admin
395 is_admin(&local_user_view)?;
398 let banned_person_id = data.person_id;
399 let ban_person = move |conn: &'_ _| Person::ban_person(conn, banned_person_id, ban);
400 if blocking(context.pool(), ban_person).await?.is_err() {
401 return Err(ApiError::err("couldnt_update_user").into());
404 // Remove their data if that's desired
405 if data.remove_data.unwrap_or(false) {
407 blocking(context.pool(), move |conn: &'_ _| {
408 Post::update_removed_for_creator(conn, banned_person_id, None, true)
413 // Remove all communities where they're the top mod
414 // for now, remove the communities manually
415 let first_mod_communities = blocking(context.pool(), move |conn: &'_ _| {
416 CommunityModeratorView::get_community_first_mods(conn)
420 // Filter to only this banned users top communities
421 let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
423 .filter(|fmc| fmc.moderator.id == banned_person_id)
426 for first_mod_community in banned_user_first_communities {
427 blocking(context.pool(), move |conn: &'_ _| {
428 Community::update_removed(conn, first_mod_community.community.id, true)
434 blocking(context.pool(), move |conn: &'_ _| {
435 Comment::update_removed_for_creator(conn, banned_person_id, true)
441 let expires = data.expires.map(naive_from_unix);
443 let form = ModBanForm {
444 mod_person_id: local_user_view.person.id,
445 other_person_id: data.person_id,
446 reason: data.reason.to_owned(),
447 banned: Some(data.ban),
451 blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??;
453 let person_id = data.person_id;
454 let person_view = blocking(context.pool(), move |conn| {
455 PersonViewSafe::read(conn, person_id)
459 let res = BanPersonResponse {
464 context.chat_server().do_send(SendAllMessage {
465 op: UserOperation::BanPerson,
466 response: res.clone(),
474 #[async_trait::async_trait(?Send)]
475 impl Perform for GetReplies {
476 type Response = GetRepliesResponse;
480 context: &Data<LemmyContext>,
481 _websocket_id: Option<ConnectionId>,
482 ) -> Result<GetRepliesResponse, LemmyError> {
483 let data: &GetReplies = self;
484 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
486 let sort: Option<SortType> = from_opt_str_to_opt_enum(&data.sort);
488 let page = data.page;
489 let limit = data.limit;
490 let unread_only = data.unread_only;
491 let person_id = local_user_view.person.id;
492 let show_bot_accounts = local_user_view.local_user.show_bot_accounts;
494 let replies = blocking(context.pool(), move |conn| {
495 CommentQueryBuilder::create(conn)
497 .unread_only(unread_only)
498 .recipient_id(person_id)
499 .show_bot_accounts(show_bot_accounts)
500 .my_person_id(person_id)
507 Ok(GetRepliesResponse { replies })
511 #[async_trait::async_trait(?Send)]
512 impl Perform for GetPersonMentions {
513 type Response = GetPersonMentionsResponse;
517 context: &Data<LemmyContext>,
518 _websocket_id: Option<ConnectionId>,
519 ) -> Result<GetPersonMentionsResponse, LemmyError> {
520 let data: &GetPersonMentions = self;
521 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
523 let sort: Option<SortType> = from_opt_str_to_opt_enum(&data.sort);
525 let page = data.page;
526 let limit = data.limit;
527 let unread_only = data.unread_only;
528 let person_id = local_user_view.person.id;
529 let mentions = blocking(context.pool(), move |conn| {
530 PersonMentionQueryBuilder::create(conn)
531 .recipient_id(person_id)
532 .my_person_id(person_id)
534 .unread_only(unread_only)
541 Ok(GetPersonMentionsResponse { mentions })
545 #[async_trait::async_trait(?Send)]
546 impl Perform for MarkPersonMentionAsRead {
547 type Response = PersonMentionResponse;
551 context: &Data<LemmyContext>,
552 _websocket_id: Option<ConnectionId>,
553 ) -> Result<PersonMentionResponse, LemmyError> {
554 let data: &MarkPersonMentionAsRead = self;
555 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
557 let person_mention_id = data.person_mention_id;
558 let read_person_mention = blocking(context.pool(), move |conn| {
559 PersonMention::read(conn, person_mention_id)
563 if local_user_view.person.id != read_person_mention.recipient_id {
564 return Err(ApiError::err("couldnt_update_comment").into());
567 let person_mention_id = read_person_mention.id;
568 let read = data.read;
570 move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read);
571 if blocking(context.pool(), update_mention).await?.is_err() {
572 return Err(ApiError::err("couldnt_update_comment").into());
575 let person_mention_id = read_person_mention.id;
576 let person_id = local_user_view.person.id;
577 let person_mention_view = blocking(context.pool(), move |conn| {
578 PersonMentionView::read(conn, person_mention_id, Some(person_id))
582 Ok(PersonMentionResponse {
588 #[async_trait::async_trait(?Send)]
589 impl Perform for MarkAllAsRead {
590 type Response = GetRepliesResponse;
594 context: &Data<LemmyContext>,
595 _websocket_id: Option<ConnectionId>,
596 ) -> Result<GetRepliesResponse, LemmyError> {
597 let data: &MarkAllAsRead = self;
598 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
600 let person_id = local_user_view.person.id;
601 let replies = blocking(context.pool(), move |conn| {
602 CommentQueryBuilder::create(conn)
603 .my_person_id(person_id)
604 .recipient_id(person_id)
612 // TODO: this should probably be a bulk operation
613 // Not easy to do as a bulk operation,
614 // because recipient_id isn't in the comment table
615 for comment_view in &replies {
616 let reply_id = comment_view.comment.id;
617 let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true);
618 if blocking(context.pool(), mark_as_read).await?.is_err() {
619 return Err(ApiError::err("couldnt_update_comment").into());
623 // Mark all user mentions as read
624 let update_person_mentions =
625 move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id);
626 if blocking(context.pool(), update_person_mentions)
630 return Err(ApiError::err("couldnt_update_comment").into());
633 // Mark all private_messages as read
634 let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id);
635 if blocking(context.pool(), update_pm).await?.is_err() {
636 return Err(ApiError::err("couldnt_update_private_message").into());
639 Ok(GetRepliesResponse { replies: vec![] })
643 #[async_trait::async_trait(?Send)]
644 impl Perform for PasswordReset {
645 type Response = PasswordResetResponse;
649 context: &Data<LemmyContext>,
650 _websocket_id: Option<ConnectionId>,
651 ) -> Result<PasswordResetResponse, LemmyError> {
652 let data: &PasswordReset = self;
655 let email = data.email.clone();
656 let local_user_view = blocking(context.pool(), move |conn| {
657 LocalUserView::find_by_email(conn, &email)
660 .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
662 // Generate a random token
663 let token = generate_random_string();
666 let token2 = token.clone();
667 let local_user_id = local_user_view.local_user.id;
668 blocking(context.pool(), move |conn| {
669 PasswordResetRequest::create_token(conn, local_user_id, &token2)
673 // Email the pure token to the user.
674 // TODO no i18n support here.
675 let email = &local_user_view.local_user.email.expect("email");
676 let subject = &format!("Password reset for {}", local_user_view.person.name);
677 let hostname = &Settings::get().get_protocol_and_hostname();
678 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);
679 send_email(subject, email, &local_user_view.person.name, html)
680 .map_err(|e| ApiError::err(&e))?;
682 Ok(PasswordResetResponse {})
686 #[async_trait::async_trait(?Send)]
687 impl Perform for PasswordChange {
688 type Response = LoginResponse;
692 context: &Data<LemmyContext>,
693 _websocket_id: Option<ConnectionId>,
694 ) -> Result<LoginResponse, LemmyError> {
695 let data: &PasswordChange = self;
697 // Fetch the user_id from the token
698 let token = data.token.clone();
699 let local_user_id = blocking(context.pool(), move |conn| {
700 PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id)
704 password_length_check(&data.password)?;
706 // Make sure passwords match
707 if data.password != data.password_verify {
708 return Err(ApiError::err("passwords_dont_match").into());
711 // Update the user with the new password
712 let password = data.password.clone();
713 let updated_local_user = blocking(context.pool(), move |conn| {
714 LocalUser::update_password(conn, local_user_id, &password)
717 .map_err(|_| ApiError::err("couldnt_update_user"))?;
721 jwt: Claims::jwt(updated_local_user.id.0)?,
726 #[async_trait::async_trait(?Send)]
727 impl Perform for GetReportCount {
728 type Response = GetReportCountResponse;
732 context: &Data<LemmyContext>,
733 websocket_id: Option<ConnectionId>,
734 ) -> Result<GetReportCountResponse, LemmyError> {
735 let data: &GetReportCount = self;
736 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
738 let person_id = local_user_view.person.id;
739 let community_id = data.community;
741 collect_moderated_communities(person_id, community_id, context.pool()).await?;
744 if community_ids.is_empty() {
745 GetReportCountResponse {
751 let ids = community_ids.clone();
752 let comment_reports = blocking(context.pool(), move |conn| {
753 CommentReportView::get_report_count(conn, &ids)
757 let ids = community_ids.clone();
758 let post_reports = blocking(context.pool(), move |conn| {
759 PostReportView::get_report_count(conn, &ids)
763 GetReportCountResponse {
764 community: data.community,
771 context.chat_server().do_send(SendUserRoomMessage {
772 op: UserOperation::GetReportCount,
773 response: res.clone(),
774 local_recipient_id: local_user_view.local_user.id,
782 #[async_trait::async_trait(?Send)]
783 impl Perform for GetFollowedCommunities {
784 type Response = GetFollowedCommunitiesResponse;
788 context: &Data<LemmyContext>,
789 _websocket_id: Option<ConnectionId>,
790 ) -> Result<GetFollowedCommunitiesResponse, LemmyError> {
791 let data: &GetFollowedCommunities = self;
792 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
794 let person_id = local_user_view.person.id;
795 let communities = blocking(context.pool(), move |conn| {
796 CommunityFollowerView::for_person(conn, person_id)
799 .map_err(|_| ApiError::err("system_err_login"))?;
802 Ok(GetFollowedCommunitiesResponse { communities })