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 local_user::LocalUser_,
23 password_reset_request::PasswordResetRequest_,
25 person_mention::PersonMention_,
27 private_message::PrivateMessage_,
32 use lemmy_db_schema::{
36 local_user::{LocalUser, LocalUserForm},
38 password_reset_request::*,
42 private_message::PrivateMessage,
47 comment_report_view::CommentReportView,
48 comment_view::CommentQueryBuilder,
49 local_user_view::LocalUserView,
50 post_report_view::PostReportView,
52 use lemmy_db_views_actor::{
53 community_follower_view::CommunityFollowerView,
54 person_mention_view::{PersonMentionQueryBuilder, PersonMentionView},
55 person_view::PersonViewSafe,
61 settings::structs::Settings,
62 utils::{generate_random_string, is_valid_display_name, is_valid_matrix_id, naive_from_unix},
67 use lemmy_websocket::{
68 messages::{CaptchaItem, SendAllMessage, SendUserRoomMessage},
73 #[async_trait::async_trait(?Send)]
74 impl Perform for Login {
75 type Response = LoginResponse;
79 context: &Data<LemmyContext>,
80 _websocket_id: Option<ConnectionId>,
81 ) -> Result<LoginResponse, LemmyError> {
82 let data: &Login = &self;
84 // Fetch that username / email
85 let username_or_email = data.username_or_email.clone();
86 let local_user_view = blocking(context.pool(), move |conn| {
87 LocalUserView::find_by_email_or_name(conn, &username_or_email)
90 .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
92 // Verify the password
93 let valid: bool = verify(
95 &local_user_view.local_user.password_encrypted,
99 return Err(ApiError::err("password_incorrect").into());
104 jwt: Claims::jwt(local_user_view.local_user.id.0)?,
109 #[async_trait::async_trait(?Send)]
110 impl Perform for GetCaptcha {
111 type Response = GetCaptchaResponse;
115 context: &Data<LemmyContext>,
116 _websocket_id: Option<ConnectionId>,
117 ) -> Result<Self::Response, LemmyError> {
118 let captcha_settings = Settings::get().captcha();
120 if !captcha_settings.enabled {
121 return Ok(GetCaptchaResponse { ok: None });
124 let captcha = match captcha_settings.difficulty.as_str() {
125 "easy" => gen(Difficulty::Easy),
126 "medium" => gen(Difficulty::Medium),
127 "hard" => gen(Difficulty::Hard),
128 _ => gen(Difficulty::Medium),
131 let answer = captcha.chars_as_string();
133 let png = captcha.as_base64().expect("failed to generate captcha");
135 let uuid = uuid::Uuid::new_v4().to_string();
137 let wav = captcha_as_wav_base64(&captcha);
139 let captcha_item = CaptchaItem {
141 uuid: uuid.to_owned(),
142 expires: naive_now() + Duration::minutes(10), // expires in 10 minutes
145 // Stores the captcha item on the queue
146 context.chat_server().do_send(captcha_item);
148 Ok(GetCaptchaResponse {
149 ok: Some(CaptchaResponse { png, wav, uuid }),
154 #[async_trait::async_trait(?Send)]
155 impl Perform for SaveUserSettings {
156 type Response = LoginResponse;
160 context: &Data<LemmyContext>,
161 _websocket_id: Option<ConnectionId>,
162 ) -> Result<LoginResponse, LemmyError> {
163 let data: &SaveUserSettings = &self;
164 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
166 let avatar = diesel_option_overwrite_to_url(&data.avatar)?;
167 let banner = diesel_option_overwrite_to_url(&data.banner)?;
168 let email = diesel_option_overwrite(&data.email);
169 let bio = diesel_option_overwrite(&data.bio);
170 let display_name = diesel_option_overwrite(&data.display_name);
171 let matrix_user_id = diesel_option_overwrite(&data.matrix_user_id);
172 let bot_account = data.bot_account;
174 if let Some(Some(bio)) = &bio {
175 if bio.chars().count() > 300 {
176 return Err(ApiError::err("bio_length_overflow").into());
180 if let Some(Some(display_name)) = &display_name {
181 if !is_valid_display_name(display_name.trim()) {
182 return Err(ApiError::err("invalid_username").into());
186 if let Some(Some(matrix_user_id)) = &matrix_user_id {
187 if !is_valid_matrix_id(matrix_user_id) {
188 return Err(ApiError::err("invalid_matrix_id").into());
192 let local_user_id = local_user_view.local_user.id;
193 let person_id = local_user_view.person.id;
194 let default_listing_type = data.default_listing_type;
195 let default_sort_type = data.default_sort_type;
196 let password_encrypted = local_user_view.local_user.password_encrypted;
198 let person_form = PersonForm {
199 name: local_user_view.person.name,
205 updated: Some(naive_now()),
214 last_refreshed_at: None,
215 shared_inbox_url: None,
220 let person_res = blocking(context.pool(), move |conn| {
221 Person::update(conn, person_id, &person_form)
224 let _updated_person: Person = match person_res {
227 return Err(ApiError::err("user_already_exists").into());
231 let local_user_form = LocalUserForm {
235 show_nsfw: data.show_nsfw,
236 show_bot_accounts: data.show_bot_accounts,
237 show_scores: data.show_scores,
238 theme: data.theme.to_owned(),
240 default_listing_type,
241 lang: data.lang.to_owned(),
242 show_avatars: data.show_avatars,
243 send_notifications_to_email: data.send_notifications_to_email,
246 let local_user_res = blocking(context.pool(), move |conn| {
247 LocalUser::update(conn, local_user_id, &local_user_form)
250 let updated_local_user = match local_user_res {
253 let err_type = if e.to_string()
254 == "duplicate key value violates unique constraint \"local_user_email_key\""
256 "email_already_exists"
258 "user_already_exists"
261 return Err(ApiError::err(err_type).into());
267 jwt: Claims::jwt(updated_local_user.id.0)?,
272 #[async_trait::async_trait(?Send)]
273 impl Perform for ChangePassword {
274 type Response = LoginResponse;
278 context: &Data<LemmyContext>,
279 _websocket_id: Option<ConnectionId>,
280 ) -> Result<LoginResponse, LemmyError> {
281 let data: &ChangePassword = &self;
282 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
284 password_length_check(&data.new_password)?;
286 // Make sure passwords match
287 if data.new_password != data.new_password_verify {
288 return Err(ApiError::err("passwords_dont_match").into());
291 // Check the old password
292 let valid: bool = verify(
294 &local_user_view.local_user.password_encrypted,
298 return Err(ApiError::err("password_incorrect").into());
301 let local_user_id = local_user_view.local_user.id;
302 let new_password = data.new_password.to_owned();
303 let updated_local_user = blocking(context.pool(), move |conn| {
304 LocalUser::update_password(conn, local_user_id, &new_password)
310 jwt: Claims::jwt(updated_local_user.id.0)?,
315 #[async_trait::async_trait(?Send)]
316 impl Perform for AddAdmin {
317 type Response = AddAdminResponse;
321 context: &Data<LemmyContext>,
322 websocket_id: Option<ConnectionId>,
323 ) -> Result<AddAdminResponse, LemmyError> {
324 let data: &AddAdmin = &self;
325 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
327 // Make sure user is an admin
328 is_admin(&local_user_view)?;
330 let added = data.added;
331 let added_person_id = data.person_id;
332 let added_admin = match blocking(context.pool(), move |conn| {
333 Person::add_admin(conn, added_person_id, added)
339 return Err(ApiError::err("couldnt_update_user").into());
344 let form = ModAddForm {
345 mod_person_id: local_user_view.person.id,
346 other_person_id: added_admin.id,
347 removed: Some(!data.added),
350 blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
352 let site_creator_id = blocking(context.pool(), move |conn| {
353 Site::read(conn, 1).map(|s| s.creator_id)
357 let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
358 let creator_index = admins
360 .position(|r| r.person.id == site_creator_id)
361 .context(location_info!())?;
362 let creator_person = admins.remove(creator_index);
363 admins.insert(0, creator_person);
365 let res = AddAdminResponse { admins };
367 context.chat_server().do_send(SendAllMessage {
368 op: UserOperation::AddAdmin,
369 response: res.clone(),
377 #[async_trait::async_trait(?Send)]
378 impl Perform for BanPerson {
379 type Response = BanPersonResponse;
383 context: &Data<LemmyContext>,
384 websocket_id: Option<ConnectionId>,
385 ) -> Result<BanPersonResponse, LemmyError> {
386 let data: &BanPerson = &self;
387 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
389 // Make sure user is an admin
390 is_admin(&local_user_view)?;
393 let banned_person_id = data.person_id;
394 let ban_person = move |conn: &'_ _| Person::ban_person(conn, banned_person_id, ban);
395 if blocking(context.pool(), ban_person).await?.is_err() {
396 return Err(ApiError::err("couldnt_update_user").into());
399 // Remove their data if that's desired
400 if data.remove_data.unwrap_or_default() {
402 blocking(context.pool(), move |conn: &'_ _| {
403 Post::update_removed_for_creator(conn, banned_person_id, None, true)
408 // Remove all communities where they're the top mod
409 // TODO couldn't get group by's working in diesel,
410 // for now, remove the communities manually
413 blocking(context.pool(), move |conn: &'_ _| {
414 Comment::update_removed_for_creator(conn, banned_person_id, true)
420 let expires = data.expires.map(naive_from_unix);
422 let form = ModBanForm {
423 mod_person_id: local_user_view.person.id,
424 other_person_id: data.person_id,
425 reason: data.reason.to_owned(),
426 banned: Some(data.ban),
430 blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??;
432 let person_id = data.person_id;
433 let person_view = blocking(context.pool(), move |conn| {
434 PersonViewSafe::read(conn, person_id)
438 let res = BanPersonResponse {
443 context.chat_server().do_send(SendAllMessage {
444 op: UserOperation::BanPerson,
445 response: res.clone(),
453 #[async_trait::async_trait(?Send)]
454 impl Perform for GetReplies {
455 type Response = GetRepliesResponse;
459 context: &Data<LemmyContext>,
460 _websocket_id: Option<ConnectionId>,
461 ) -> Result<GetRepliesResponse, LemmyError> {
462 let data: &GetReplies = &self;
463 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
465 let sort: Option<SortType> = from_opt_str_to_opt_enum(&data.sort);
467 let page = data.page;
468 let limit = data.limit;
469 let unread_only = data.unread_only;
470 let person_id = local_user_view.person.id;
471 let show_bot_accounts = local_user_view.local_user.show_bot_accounts;
473 let replies = blocking(context.pool(), move |conn| {
474 CommentQueryBuilder::create(conn)
476 .unread_only(unread_only)
477 .recipient_id(person_id)
478 .show_bot_accounts(show_bot_accounts)
479 .my_person_id(person_id)
486 Ok(GetRepliesResponse { replies })
490 #[async_trait::async_trait(?Send)]
491 impl Perform for GetPersonMentions {
492 type Response = GetPersonMentionsResponse;
496 context: &Data<LemmyContext>,
497 _websocket_id: Option<ConnectionId>,
498 ) -> Result<GetPersonMentionsResponse, LemmyError> {
499 let data: &GetPersonMentions = &self;
500 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
502 let sort: Option<SortType> = from_opt_str_to_opt_enum(&data.sort);
504 let page = data.page;
505 let limit = data.limit;
506 let unread_only = data.unread_only;
507 let person_id = local_user_view.person.id;
508 let mentions = blocking(context.pool(), move |conn| {
509 PersonMentionQueryBuilder::create(conn)
510 .recipient_id(person_id)
511 .my_person_id(person_id)
513 .unread_only(unread_only)
520 Ok(GetPersonMentionsResponse { mentions })
524 #[async_trait::async_trait(?Send)]
525 impl Perform for MarkPersonMentionAsRead {
526 type Response = PersonMentionResponse;
530 context: &Data<LemmyContext>,
531 _websocket_id: Option<ConnectionId>,
532 ) -> Result<PersonMentionResponse, LemmyError> {
533 let data: &MarkPersonMentionAsRead = &self;
534 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
536 let person_mention_id = data.person_mention_id;
537 let read_person_mention = blocking(context.pool(), move |conn| {
538 PersonMention::read(conn, person_mention_id)
542 if local_user_view.person.id != read_person_mention.recipient_id {
543 return Err(ApiError::err("couldnt_update_comment").into());
546 let person_mention_id = read_person_mention.id;
547 let read = data.read;
549 move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read);
550 if blocking(context.pool(), update_mention).await?.is_err() {
551 return Err(ApiError::err("couldnt_update_comment").into());
554 let person_mention_id = read_person_mention.id;
555 let person_id = local_user_view.person.id;
556 let person_mention_view = blocking(context.pool(), move |conn| {
557 PersonMentionView::read(conn, person_mention_id, Some(person_id))
561 Ok(PersonMentionResponse {
567 #[async_trait::async_trait(?Send)]
568 impl Perform for MarkAllAsRead {
569 type Response = GetRepliesResponse;
573 context: &Data<LemmyContext>,
574 _websocket_id: Option<ConnectionId>,
575 ) -> Result<GetRepliesResponse, LemmyError> {
576 let data: &MarkAllAsRead = &self;
577 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
579 let person_id = local_user_view.person.id;
580 let replies = blocking(context.pool(), move |conn| {
581 CommentQueryBuilder::create(conn)
582 .my_person_id(person_id)
583 .recipient_id(person_id)
591 // TODO: this should probably be a bulk operation
592 // Not easy to do as a bulk operation,
593 // because recipient_id isn't in the comment table
594 for comment_view in &replies {
595 let reply_id = comment_view.comment.id;
596 let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true);
597 if blocking(context.pool(), mark_as_read).await?.is_err() {
598 return Err(ApiError::err("couldnt_update_comment").into());
602 // Mark all user mentions as read
603 let update_person_mentions =
604 move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id);
605 if blocking(context.pool(), update_person_mentions)
609 return Err(ApiError::err("couldnt_update_comment").into());
612 // Mark all private_messages as read
613 let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id);
614 if blocking(context.pool(), update_pm).await?.is_err() {
615 return Err(ApiError::err("couldnt_update_private_message").into());
618 Ok(GetRepliesResponse { replies: vec![] })
622 #[async_trait::async_trait(?Send)]
623 impl Perform for PasswordReset {
624 type Response = PasswordResetResponse;
628 context: &Data<LemmyContext>,
629 _websocket_id: Option<ConnectionId>,
630 ) -> Result<PasswordResetResponse, LemmyError> {
631 let data: &PasswordReset = &self;
634 let email = data.email.clone();
635 let local_user_view = blocking(context.pool(), move |conn| {
636 LocalUserView::find_by_email(conn, &email)
639 .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
641 // Generate a random token
642 let token = generate_random_string();
645 let token2 = token.clone();
646 let local_user_id = local_user_view.local_user.id;
647 blocking(context.pool(), move |conn| {
648 PasswordResetRequest::create_token(conn, local_user_id, &token2)
652 // Email the pure token to the user.
653 // TODO no i18n support here.
654 let email = &local_user_view.local_user.email.expect("email");
655 let subject = &format!("Password reset for {}", local_user_view.person.name);
656 let hostname = &Settings::get().get_protocol_and_hostname();
657 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);
658 send_email(subject, email, &local_user_view.person.name, html)
659 .map_err(|e| ApiError::err(&e))?;
661 Ok(PasswordResetResponse {})
665 #[async_trait::async_trait(?Send)]
666 impl Perform for PasswordChange {
667 type Response = LoginResponse;
671 context: &Data<LemmyContext>,
672 _websocket_id: Option<ConnectionId>,
673 ) -> Result<LoginResponse, LemmyError> {
674 let data: &PasswordChange = &self;
676 // Fetch the user_id from the token
677 let token = data.token.clone();
678 let local_user_id = blocking(context.pool(), move |conn| {
679 PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id)
683 password_length_check(&data.password)?;
685 // Make sure passwords match
686 if data.password != data.password_verify {
687 return Err(ApiError::err("passwords_dont_match").into());
690 // Update the user with the new password
691 let password = data.password.clone();
692 let updated_local_user = blocking(context.pool(), move |conn| {
693 LocalUser::update_password(conn, local_user_id, &password)
696 .map_err(|_| ApiError::err("couldnt_update_user"))?;
700 jwt: Claims::jwt(updated_local_user.id.0)?,
705 #[async_trait::async_trait(?Send)]
706 impl Perform for GetReportCount {
707 type Response = GetReportCountResponse;
711 context: &Data<LemmyContext>,
712 websocket_id: Option<ConnectionId>,
713 ) -> Result<GetReportCountResponse, LemmyError> {
714 let data: &GetReportCount = &self;
715 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
717 let person_id = local_user_view.person.id;
718 let community_id = data.community;
720 collect_moderated_communities(person_id, community_id, context.pool()).await?;
723 if community_ids.is_empty() {
724 GetReportCountResponse {
730 let ids = community_ids.clone();
731 let comment_reports = blocking(context.pool(), move |conn| {
732 CommentReportView::get_report_count(conn, &ids)
736 let ids = community_ids.clone();
737 let post_reports = blocking(context.pool(), move |conn| {
738 PostReportView::get_report_count(conn, &ids)
742 GetReportCountResponse {
743 community: data.community,
750 context.chat_server().do_send(SendUserRoomMessage {
751 op: UserOperation::GetReportCount,
752 response: res.clone(),
753 local_recipient_id: local_user_view.local_user.id,
761 #[async_trait::async_trait(?Send)]
762 impl Perform for GetFollowedCommunities {
763 type Response = GetFollowedCommunitiesResponse;
767 context: &Data<LemmyContext>,
768 _websocket_id: Option<ConnectionId>,
769 ) -> Result<GetFollowedCommunitiesResponse, LemmyError> {
770 let data: &GetFollowedCommunities = &self;
771 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
773 let person_id = local_user_view.person.id;
774 let communities = blocking(context.pool(), move |conn| {
775 CommunityFollowerView::for_person(conn, person_id)
778 .map_err(|_| ApiError::err("system_err_login"))?;
781 Ok(GetFollowedCommunitiesResponse { communities })