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);
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 show_read_posts: data.show_read_posts,
244 send_notifications_to_email: data.send_notifications_to_email,
247 let local_user_res = blocking(context.pool(), move |conn| {
248 LocalUser::update(conn, local_user_id, &local_user_form)
251 let updated_local_user = match local_user_res {
254 let err_type = if e.to_string()
255 == "duplicate key value violates unique constraint \"local_user_email_key\""
257 "email_already_exists"
259 "user_already_exists"
262 return Err(ApiError::err(err_type).into());
268 jwt: Claims::jwt(updated_local_user.id.0)?,
273 #[async_trait::async_trait(?Send)]
274 impl Perform for ChangePassword {
275 type Response = LoginResponse;
279 context: &Data<LemmyContext>,
280 _websocket_id: Option<ConnectionId>,
281 ) -> Result<LoginResponse, LemmyError> {
282 let data: &ChangePassword = &self;
283 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
285 password_length_check(&data.new_password)?;
287 // Make sure passwords match
288 if data.new_password != data.new_password_verify {
289 return Err(ApiError::err("passwords_dont_match").into());
292 // Check the old password
293 let valid: bool = verify(
295 &local_user_view.local_user.password_encrypted,
299 return Err(ApiError::err("password_incorrect").into());
302 let local_user_id = local_user_view.local_user.id;
303 let new_password = data.new_password.to_owned();
304 let updated_local_user = blocking(context.pool(), move |conn| {
305 LocalUser::update_password(conn, local_user_id, &new_password)
311 jwt: Claims::jwt(updated_local_user.id.0)?,
316 #[async_trait::async_trait(?Send)]
317 impl Perform for AddAdmin {
318 type Response = AddAdminResponse;
322 context: &Data<LemmyContext>,
323 websocket_id: Option<ConnectionId>,
324 ) -> Result<AddAdminResponse, LemmyError> {
325 let data: &AddAdmin = &self;
326 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
328 // Make sure user is an admin
329 is_admin(&local_user_view)?;
331 let added = data.added;
332 let added_person_id = data.person_id;
333 let added_admin = match blocking(context.pool(), move |conn| {
334 Person::add_admin(conn, added_person_id, added)
340 return Err(ApiError::err("couldnt_update_user").into());
345 let form = ModAddForm {
346 mod_person_id: local_user_view.person.id,
347 other_person_id: added_admin.id,
348 removed: Some(!data.added),
351 blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
353 let site_creator_id = blocking(context.pool(), move |conn| {
354 Site::read(conn, 1).map(|s| s.creator_id)
358 let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
359 let creator_index = admins
361 .position(|r| r.person.id == site_creator_id)
362 .context(location_info!())?;
363 let creator_person = admins.remove(creator_index);
364 admins.insert(0, creator_person);
366 let res = AddAdminResponse { admins };
368 context.chat_server().do_send(SendAllMessage {
369 op: UserOperation::AddAdmin,
370 response: res.clone(),
378 #[async_trait::async_trait(?Send)]
379 impl Perform for BanPerson {
380 type Response = BanPersonResponse;
384 context: &Data<LemmyContext>,
385 websocket_id: Option<ConnectionId>,
386 ) -> Result<BanPersonResponse, LemmyError> {
387 let data: &BanPerson = &self;
388 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
390 // Make sure user is an admin
391 is_admin(&local_user_view)?;
394 let banned_person_id = data.person_id;
395 let ban_person = move |conn: &'_ _| Person::ban_person(conn, banned_person_id, ban);
396 if blocking(context.pool(), ban_person).await?.is_err() {
397 return Err(ApiError::err("couldnt_update_user").into());
400 // Remove their data if that's desired
401 if data.remove_data {
403 blocking(context.pool(), move |conn: &'_ _| {
404 Post::update_removed_for_creator(conn, banned_person_id, None, true)
409 // Remove all communities where they're the top mod
410 // TODO couldn't get group by's working in diesel,
411 // for now, remove the communities manually
414 blocking(context.pool(), move |conn: &'_ _| {
415 Comment::update_removed_for_creator(conn, banned_person_id, true)
421 let expires = data.expires.map(naive_from_unix);
423 let form = ModBanForm {
424 mod_person_id: local_user_view.person.id,
425 other_person_id: data.person_id,
426 reason: data.reason.to_owned(),
427 banned: Some(data.ban),
431 blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??;
433 let person_id = data.person_id;
434 let person_view = blocking(context.pool(), move |conn| {
435 PersonViewSafe::read(conn, person_id)
439 let res = BanPersonResponse {
444 context.chat_server().do_send(SendAllMessage {
445 op: UserOperation::BanPerson,
446 response: res.clone(),
454 #[async_trait::async_trait(?Send)]
455 impl Perform for GetReplies {
456 type Response = GetRepliesResponse;
460 context: &Data<LemmyContext>,
461 _websocket_id: Option<ConnectionId>,
462 ) -> Result<GetRepliesResponse, LemmyError> {
463 let data: &GetReplies = &self;
464 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
466 let sort = SortType::from_str(&data.sort)?;
468 let page = data.page;
469 let limit = data.limit;
470 let unread_only = data.unread_only;
471 let person_id = local_user_view.person.id;
472 let show_bot_accounts = local_user_view.local_user.show_bot_accounts;
474 let replies = blocking(context.pool(), move |conn| {
475 CommentQueryBuilder::create(conn)
477 .unread_only(unread_only)
478 .recipient_id(person_id)
479 .show_bot_accounts(show_bot_accounts)
480 .my_person_id(person_id)
487 Ok(GetRepliesResponse { replies })
491 #[async_trait::async_trait(?Send)]
492 impl Perform for GetPersonMentions {
493 type Response = GetPersonMentionsResponse;
497 context: &Data<LemmyContext>,
498 _websocket_id: Option<ConnectionId>,
499 ) -> Result<GetPersonMentionsResponse, LemmyError> {
500 let data: &GetPersonMentions = &self;
501 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
503 let sort = SortType::from_str(&data.sort)?;
505 let page = data.page;
506 let limit = data.limit;
507 let unread_only = data.unread_only;
508 let person_id = local_user_view.person.id;
509 let mentions = blocking(context.pool(), move |conn| {
510 PersonMentionQueryBuilder::create(conn)
511 .recipient_id(person_id)
512 .my_person_id(person_id)
514 .unread_only(unread_only)
521 Ok(GetPersonMentionsResponse { mentions })
525 #[async_trait::async_trait(?Send)]
526 impl Perform for MarkPersonMentionAsRead {
527 type Response = PersonMentionResponse;
531 context: &Data<LemmyContext>,
532 _websocket_id: Option<ConnectionId>,
533 ) -> Result<PersonMentionResponse, LemmyError> {
534 let data: &MarkPersonMentionAsRead = &self;
535 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
537 let person_mention_id = data.person_mention_id;
538 let read_person_mention = blocking(context.pool(), move |conn| {
539 PersonMention::read(conn, person_mention_id)
543 if local_user_view.person.id != read_person_mention.recipient_id {
544 return Err(ApiError::err("couldnt_update_comment").into());
547 let person_mention_id = read_person_mention.id;
548 let read = data.read;
550 move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read);
551 if blocking(context.pool(), update_mention).await?.is_err() {
552 return Err(ApiError::err("couldnt_update_comment").into());
555 let person_mention_id = read_person_mention.id;
556 let person_id = local_user_view.person.id;
557 let person_mention_view = blocking(context.pool(), move |conn| {
558 PersonMentionView::read(conn, person_mention_id, Some(person_id))
562 Ok(PersonMentionResponse {
568 #[async_trait::async_trait(?Send)]
569 impl Perform for MarkAllAsRead {
570 type Response = GetRepliesResponse;
574 context: &Data<LemmyContext>,
575 _websocket_id: Option<ConnectionId>,
576 ) -> Result<GetRepliesResponse, LemmyError> {
577 let data: &MarkAllAsRead = &self;
578 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
580 let person_id = local_user_view.person.id;
581 let replies = blocking(context.pool(), move |conn| {
582 CommentQueryBuilder::create(conn)
583 .my_person_id(person_id)
584 .recipient_id(person_id)
592 // TODO: this should probably be a bulk operation
593 // Not easy to do as a bulk operation,
594 // because recipient_id isn't in the comment table
595 for comment_view in &replies {
596 let reply_id = comment_view.comment.id;
597 let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true);
598 if blocking(context.pool(), mark_as_read).await?.is_err() {
599 return Err(ApiError::err("couldnt_update_comment").into());
603 // Mark all user mentions as read
604 let update_person_mentions =
605 move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id);
606 if blocking(context.pool(), update_person_mentions)
610 return Err(ApiError::err("couldnt_update_comment").into());
613 // Mark all private_messages as read
614 let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id);
615 if blocking(context.pool(), update_pm).await?.is_err() {
616 return Err(ApiError::err("couldnt_update_private_message").into());
619 Ok(GetRepliesResponse { replies: vec![] })
623 #[async_trait::async_trait(?Send)]
624 impl Perform for PasswordReset {
625 type Response = PasswordResetResponse;
629 context: &Data<LemmyContext>,
630 _websocket_id: Option<ConnectionId>,
631 ) -> Result<PasswordResetResponse, LemmyError> {
632 let data: &PasswordReset = &self;
635 let email = data.email.clone();
636 let local_user_view = blocking(context.pool(), move |conn| {
637 LocalUserView::find_by_email(conn, &email)
640 .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
642 // Generate a random token
643 let token = generate_random_string();
646 let token2 = token.clone();
647 let local_user_id = local_user_view.local_user.id;
648 blocking(context.pool(), move |conn| {
649 PasswordResetRequest::create_token(conn, local_user_id, &token2)
653 // Email the pure token to the user.
654 // TODO no i18n support here.
655 let email = &local_user_view.local_user.email.expect("email");
656 let subject = &format!("Password reset for {}", local_user_view.person.name);
657 let hostname = &Settings::get().get_protocol_and_hostname();
658 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);
659 send_email(subject, email, &local_user_view.person.name, html)
660 .map_err(|e| ApiError::err(&e))?;
662 Ok(PasswordResetResponse {})
666 #[async_trait::async_trait(?Send)]
667 impl Perform for PasswordChange {
668 type Response = LoginResponse;
672 context: &Data<LemmyContext>,
673 _websocket_id: Option<ConnectionId>,
674 ) -> Result<LoginResponse, LemmyError> {
675 let data: &PasswordChange = &self;
677 // Fetch the user_id from the token
678 let token = data.token.clone();
679 let local_user_id = blocking(context.pool(), move |conn| {
680 PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id)
684 password_length_check(&data.password)?;
686 // Make sure passwords match
687 if data.password != data.password_verify {
688 return Err(ApiError::err("passwords_dont_match").into());
691 // Update the user with the new password
692 let password = data.password.clone();
693 let updated_local_user = blocking(context.pool(), move |conn| {
694 LocalUser::update_password(conn, local_user_id, &password)
697 .map_err(|_| ApiError::err("couldnt_update_user"))?;
701 jwt: Claims::jwt(updated_local_user.id.0)?,
706 #[async_trait::async_trait(?Send)]
707 impl Perform for GetReportCount {
708 type Response = GetReportCountResponse;
712 context: &Data<LemmyContext>,
713 websocket_id: Option<ConnectionId>,
714 ) -> Result<GetReportCountResponse, LemmyError> {
715 let data: &GetReportCount = &self;
716 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
718 let person_id = local_user_view.person.id;
719 let community_id = data.community;
721 collect_moderated_communities(person_id, community_id, context.pool()).await?;
724 if community_ids.is_empty() {
725 GetReportCountResponse {
731 let ids = community_ids.clone();
732 let comment_reports = blocking(context.pool(), move |conn| {
733 CommentReportView::get_report_count(conn, &ids)
737 let ids = community_ids.clone();
738 let post_reports = blocking(context.pool(), move |conn| {
739 PostReportView::get_report_count(conn, &ids)
743 GetReportCountResponse {
744 community: data.community,
751 context.chat_server().do_send(SendUserRoomMessage {
752 op: UserOperation::GetReportCount,
753 response: res.clone(),
754 local_recipient_id: local_user_view.local_user.id,
762 #[async_trait::async_trait(?Send)]
763 impl Perform for GetFollowedCommunities {
764 type Response = GetFollowedCommunitiesResponse;
768 context: &Data<LemmyContext>,
769 _websocket_id: Option<ConnectionId>,
770 ) -> Result<GetFollowedCommunitiesResponse, LemmyError> {
771 let data: &GetFollowedCommunities = &self;
772 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
774 let person_id = local_user_view.person.id;
775 let communities = blocking(context.pool(), move |conn| {
776 CommunityFollowerView::for_person(conn, person_id)
779 .map_err(|_| ApiError::err("system_err_login"))?;
782 Ok(GetFollowedCommunitiesResponse { communities })