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,
21 local_user::LocalUser_,
22 password_reset_request::PasswordResetRequest_,
24 person_mention::PersonMention_,
26 private_message::PrivateMessage_,
31 use lemmy_db_schema::{
35 local_user::{LocalUser, LocalUserForm},
37 password_reset_request::*,
41 private_message::PrivateMessage,
46 comment_report_view::CommentReportView,
47 comment_view::CommentQueryBuilder,
48 local_user_view::LocalUserView,
49 post_report_view::PostReportView,
51 use lemmy_db_views_actor::{
52 community_follower_view::CommunityFollowerView,
53 person_mention_view::{PersonMentionQueryBuilder, PersonMentionView},
54 person_view::PersonViewSafe,
60 settings::structs::Settings,
61 utils::{generate_random_string, is_valid_display_name, is_valid_matrix_id, naive_from_unix},
66 use lemmy_websocket::{
67 messages::{CaptchaItem, SendAllMessage, SendUserRoomMessage},
71 use std::str::FromStr;
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);
173 if let Some(Some(bio)) = &bio {
174 if bio.chars().count() > 300 {
175 return Err(ApiError::err("bio_length_overflow").into());
179 if let Some(Some(display_name)) = &display_name {
180 if !is_valid_display_name(display_name.trim()) {
181 return Err(ApiError::err("invalid_username").into());
185 if let Some(Some(matrix_user_id)) = &matrix_user_id {
186 if !is_valid_matrix_id(matrix_user_id) {
187 return Err(ApiError::err("invalid_matrix_id").into());
191 let local_user_id = local_user_view.local_user.id;
192 let person_id = local_user_view.person.id;
193 let default_listing_type = data.default_listing_type;
194 let default_sort_type = data.default_sort_type;
195 let password_encrypted = local_user_view.local_user.password_encrypted;
197 let person_form = PersonForm {
198 name: local_user_view.person.name,
204 updated: Some(naive_now()),
213 last_refreshed_at: None,
214 shared_inbox_url: None,
218 let person_res = blocking(context.pool(), move |conn| {
219 Person::update(conn, person_id, &person_form)
222 let _updated_person: Person = match person_res {
225 return Err(ApiError::err("user_already_exists").into());
229 let local_user_form = LocalUserForm {
233 show_nsfw: data.show_nsfw,
234 show_scores: data.show_scores,
235 theme: data.theme.to_owned(),
237 default_listing_type,
238 lang: data.lang.to_owned(),
239 show_avatars: data.show_avatars,
240 send_notifications_to_email: data.send_notifications_to_email,
243 let local_user_res = blocking(context.pool(), move |conn| {
244 LocalUser::update(conn, local_user_id, &local_user_form)
247 let updated_local_user = match local_user_res {
250 let err_type = if e.to_string()
251 == "duplicate key value violates unique constraint \"local_user_email_key\""
253 "email_already_exists"
255 "user_already_exists"
258 return Err(ApiError::err(err_type).into());
264 jwt: Claims::jwt(updated_local_user.id.0)?,
269 #[async_trait::async_trait(?Send)]
270 impl Perform for ChangePassword {
271 type Response = LoginResponse;
275 context: &Data<LemmyContext>,
276 _websocket_id: Option<ConnectionId>,
277 ) -> Result<LoginResponse, LemmyError> {
278 let data: &ChangePassword = &self;
279 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
281 password_length_check(&data.new_password)?;
283 // Make sure passwords match
284 if data.new_password != data.new_password_verify {
285 return Err(ApiError::err("passwords_dont_match").into());
288 // Check the old password
289 let valid: bool = verify(
291 &local_user_view.local_user.password_encrypted,
295 return Err(ApiError::err("password_incorrect").into());
298 let local_user_id = local_user_view.local_user.id;
299 let new_password = data.new_password.to_owned();
300 let updated_local_user = blocking(context.pool(), move |conn| {
301 LocalUser::update_password(conn, local_user_id, &new_password)
307 jwt: Claims::jwt(updated_local_user.id.0)?,
312 #[async_trait::async_trait(?Send)]
313 impl Perform for AddAdmin {
314 type Response = AddAdminResponse;
318 context: &Data<LemmyContext>,
319 websocket_id: Option<ConnectionId>,
320 ) -> Result<AddAdminResponse, LemmyError> {
321 let data: &AddAdmin = &self;
322 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
324 // Make sure user is an admin
325 is_admin(&local_user_view)?;
327 let added = data.added;
328 let added_person_id = data.person_id;
329 let added_admin = match blocking(context.pool(), move |conn| {
330 Person::add_admin(conn, added_person_id, added)
336 return Err(ApiError::err("couldnt_update_user").into());
341 let form = ModAddForm {
342 mod_person_id: local_user_view.person.id,
343 other_person_id: added_admin.id,
344 removed: Some(!data.added),
347 blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
349 let site_creator_id = blocking(context.pool(), move |conn| {
350 Site::read(conn, 1).map(|s| s.creator_id)
354 let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
355 let creator_index = admins
357 .position(|r| r.person.id == site_creator_id)
358 .context(location_info!())?;
359 let creator_person = admins.remove(creator_index);
360 admins.insert(0, creator_person);
362 let res = AddAdminResponse { admins };
364 context.chat_server().do_send(SendAllMessage {
365 op: UserOperation::AddAdmin,
366 response: res.clone(),
374 #[async_trait::async_trait(?Send)]
375 impl Perform for BanPerson {
376 type Response = BanPersonResponse;
380 context: &Data<LemmyContext>,
381 websocket_id: Option<ConnectionId>,
382 ) -> Result<BanPersonResponse, LemmyError> {
383 let data: &BanPerson = &self;
384 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
386 // Make sure user is an admin
387 is_admin(&local_user_view)?;
390 let banned_person_id = data.person_id;
391 let ban_person = move |conn: &'_ _| Person::ban_person(conn, banned_person_id, ban);
392 if blocking(context.pool(), ban_person).await?.is_err() {
393 return Err(ApiError::err("couldnt_update_user").into());
396 // Remove their data if that's desired
397 if data.remove_data {
399 blocking(context.pool(), move |conn: &'_ _| {
400 Post::update_removed_for_creator(conn, banned_person_id, None, true)
405 // Remove all communities where they're the top mod
406 // TODO couldn't get group by's working in diesel,
407 // for now, remove the communities manually
410 blocking(context.pool(), move |conn: &'_ _| {
411 Comment::update_removed_for_creator(conn, banned_person_id, true)
417 let expires = data.expires.map(naive_from_unix);
419 let form = ModBanForm {
420 mod_person_id: local_user_view.person.id,
421 other_person_id: data.person_id,
422 reason: data.reason.to_owned(),
423 banned: Some(data.ban),
427 blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??;
429 let person_id = data.person_id;
430 let person_view = blocking(context.pool(), move |conn| {
431 PersonViewSafe::read(conn, person_id)
435 let res = BanPersonResponse {
440 context.chat_server().do_send(SendAllMessage {
441 op: UserOperation::BanPerson,
442 response: res.clone(),
450 #[async_trait::async_trait(?Send)]
451 impl Perform for GetReplies {
452 type Response = GetRepliesResponse;
456 context: &Data<LemmyContext>,
457 _websocket_id: Option<ConnectionId>,
458 ) -> Result<GetRepliesResponse, LemmyError> {
459 let data: &GetReplies = &self;
460 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
462 let sort = SortType::from_str(&data.sort)?;
464 let page = data.page;
465 let limit = data.limit;
466 let unread_only = data.unread_only;
467 let person_id = local_user_view.person.id;
468 let replies = blocking(context.pool(), move |conn| {
469 CommentQueryBuilder::create(conn)
471 .unread_only(unread_only)
472 .recipient_id(person_id)
473 .my_person_id(person_id)
480 Ok(GetRepliesResponse { replies })
484 #[async_trait::async_trait(?Send)]
485 impl Perform for GetPersonMentions {
486 type Response = GetPersonMentionsResponse;
490 context: &Data<LemmyContext>,
491 _websocket_id: Option<ConnectionId>,
492 ) -> Result<GetPersonMentionsResponse, LemmyError> {
493 let data: &GetPersonMentions = &self;
494 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
496 let sort = SortType::from_str(&data.sort)?;
498 let page = data.page;
499 let limit = data.limit;
500 let unread_only = data.unread_only;
501 let person_id = local_user_view.person.id;
502 let mentions = blocking(context.pool(), move |conn| {
503 PersonMentionQueryBuilder::create(conn)
504 .recipient_id(person_id)
505 .my_person_id(person_id)
507 .unread_only(unread_only)
514 Ok(GetPersonMentionsResponse { mentions })
518 #[async_trait::async_trait(?Send)]
519 impl Perform for MarkPersonMentionAsRead {
520 type Response = PersonMentionResponse;
524 context: &Data<LemmyContext>,
525 _websocket_id: Option<ConnectionId>,
526 ) -> Result<PersonMentionResponse, LemmyError> {
527 let data: &MarkPersonMentionAsRead = &self;
528 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
530 let person_mention_id = data.person_mention_id;
531 let read_person_mention = blocking(context.pool(), move |conn| {
532 PersonMention::read(conn, person_mention_id)
536 if local_user_view.person.id != read_person_mention.recipient_id {
537 return Err(ApiError::err("couldnt_update_comment").into());
540 let person_mention_id = read_person_mention.id;
541 let read = data.read;
543 move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read);
544 if blocking(context.pool(), update_mention).await?.is_err() {
545 return Err(ApiError::err("couldnt_update_comment").into());
548 let person_mention_id = read_person_mention.id;
549 let person_id = local_user_view.person.id;
550 let person_mention_view = blocking(context.pool(), move |conn| {
551 PersonMentionView::read(conn, person_mention_id, Some(person_id))
555 Ok(PersonMentionResponse {
561 #[async_trait::async_trait(?Send)]
562 impl Perform for MarkAllAsRead {
563 type Response = GetRepliesResponse;
567 context: &Data<LemmyContext>,
568 _websocket_id: Option<ConnectionId>,
569 ) -> Result<GetRepliesResponse, LemmyError> {
570 let data: &MarkAllAsRead = &self;
571 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
573 let person_id = local_user_view.person.id;
574 let replies = blocking(context.pool(), move |conn| {
575 CommentQueryBuilder::create(conn)
576 .my_person_id(person_id)
577 .recipient_id(person_id)
585 // TODO: this should probably be a bulk operation
586 // Not easy to do as a bulk operation,
587 // because recipient_id isn't in the comment table
588 for comment_view in &replies {
589 let reply_id = comment_view.comment.id;
590 let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true);
591 if blocking(context.pool(), mark_as_read).await?.is_err() {
592 return Err(ApiError::err("couldnt_update_comment").into());
596 // Mark all user mentions as read
597 let update_person_mentions =
598 move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id);
599 if blocking(context.pool(), update_person_mentions)
603 return Err(ApiError::err("couldnt_update_comment").into());
606 // Mark all private_messages as read
607 let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id);
608 if blocking(context.pool(), update_pm).await?.is_err() {
609 return Err(ApiError::err("couldnt_update_private_message").into());
612 Ok(GetRepliesResponse { replies: vec![] })
616 #[async_trait::async_trait(?Send)]
617 impl Perform for PasswordReset {
618 type Response = PasswordResetResponse;
622 context: &Data<LemmyContext>,
623 _websocket_id: Option<ConnectionId>,
624 ) -> Result<PasswordResetResponse, LemmyError> {
625 let data: &PasswordReset = &self;
628 let email = data.email.clone();
629 let local_user_view = blocking(context.pool(), move |conn| {
630 LocalUserView::find_by_email(conn, &email)
633 .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
635 // Generate a random token
636 let token = generate_random_string();
639 let token2 = token.clone();
640 let local_user_id = local_user_view.local_user.id;
641 blocking(context.pool(), move |conn| {
642 PasswordResetRequest::create_token(conn, local_user_id, &token2)
646 // Email the pure token to the user.
647 // TODO no i18n support here.
648 let email = &local_user_view.local_user.email.expect("email");
649 let subject = &format!("Password reset for {}", local_user_view.person.name);
650 let hostname = &Settings::get().get_protocol_and_hostname();
651 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);
652 send_email(subject, email, &local_user_view.person.name, html)
653 .map_err(|e| ApiError::err(&e))?;
655 Ok(PasswordResetResponse {})
659 #[async_trait::async_trait(?Send)]
660 impl Perform for PasswordChange {
661 type Response = LoginResponse;
665 context: &Data<LemmyContext>,
666 _websocket_id: Option<ConnectionId>,
667 ) -> Result<LoginResponse, LemmyError> {
668 let data: &PasswordChange = &self;
670 // Fetch the user_id from the token
671 let token = data.token.clone();
672 let local_user_id = blocking(context.pool(), move |conn| {
673 PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id)
677 password_length_check(&data.password)?;
679 // Make sure passwords match
680 if data.password != data.password_verify {
681 return Err(ApiError::err("passwords_dont_match").into());
684 // Update the user with the new password
685 let password = data.password.clone();
686 let updated_local_user = blocking(context.pool(), move |conn| {
687 LocalUser::update_password(conn, local_user_id, &password)
690 .map_err(|_| ApiError::err("couldnt_update_user"))?;
694 jwt: Claims::jwt(updated_local_user.id.0)?,
699 #[async_trait::async_trait(?Send)]
700 impl Perform for GetReportCount {
701 type Response = GetReportCountResponse;
705 context: &Data<LemmyContext>,
706 websocket_id: Option<ConnectionId>,
707 ) -> Result<GetReportCountResponse, LemmyError> {
708 let data: &GetReportCount = &self;
709 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
711 let person_id = local_user_view.person.id;
712 let community_id = data.community;
714 collect_moderated_communities(person_id, community_id, context.pool()).await?;
717 if community_ids.is_empty() {
718 GetReportCountResponse {
724 let ids = community_ids.clone();
725 let comment_reports = blocking(context.pool(), move |conn| {
726 CommentReportView::get_report_count(conn, &ids)
730 let ids = community_ids.clone();
731 let post_reports = blocking(context.pool(), move |conn| {
732 PostReportView::get_report_count(conn, &ids)
736 GetReportCountResponse {
737 community: data.community,
744 context.chat_server().do_send(SendUserRoomMessage {
745 op: UserOperation::GetReportCount,
746 response: res.clone(),
747 local_recipient_id: local_user_view.local_user.id,
755 #[async_trait::async_trait(?Send)]
756 impl Perform for GetFollowedCommunities {
757 type Response = GetFollowedCommunitiesResponse;
761 context: &Data<LemmyContext>,
762 _websocket_id: Option<ConnectionId>,
763 ) -> Result<GetFollowedCommunitiesResponse, LemmyError> {
764 let data: &GetFollowedCommunities = &self;
765 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
767 let person_id = local_user_view.person.id;
768 let communities = blocking(context.pool(), move |conn| {
769 CommunityFollowerView::for_person(conn, person_id)
772 .map_err(|_| ApiError::err("system_err_login"))?;
775 Ok(GetFollowedCommunitiesResponse { communities })