]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/save_settings.rs
Dont return error in case optional auth is invalid (#2879)
[lemmy.git] / crates / api / src / local_user / save_settings.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   context::LemmyContext,
5   person::{LoginResponse, SaveUserSettings},
6   utils::{local_user_view_from_jwt, send_verification_email},
7 };
8 use lemmy_db_schema::{
9   source::{
10     actor_language::LocalUserLanguage,
11     local_user::{LocalUser, LocalUserUpdateForm},
12     person::{Person, PersonUpdateForm},
13   },
14   traits::Crud,
15   utils::{diesel_option_overwrite, diesel_option_overwrite_to_url},
16 };
17 use lemmy_db_views::structs::SiteView;
18 use lemmy_utils::{
19   claims::Claims,
20   error::LemmyError,
21   utils::validation::{
22     build_totp_2fa,
23     generate_totp_2fa_secret,
24     is_valid_bio_field,
25     is_valid_display_name,
26     is_valid_matrix_id,
27   },
28   ConnectionId,
29 };
30
31 #[async_trait::async_trait(?Send)]
32 impl Perform for SaveUserSettings {
33   type Response = LoginResponse;
34
35   #[tracing::instrument(skip(context, _websocket_id))]
36   async fn perform(
37     &self,
38     context: &Data<LemmyContext>,
39     _websocket_id: Option<ConnectionId>,
40   ) -> Result<LoginResponse, LemmyError> {
41     let data: &SaveUserSettings = self;
42     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
43     let site_view = SiteView::read_local(context.pool()).await?;
44
45     let avatar = diesel_option_overwrite_to_url(&data.avatar)?;
46     let banner = diesel_option_overwrite_to_url(&data.banner)?;
47     let bio = diesel_option_overwrite(&data.bio);
48     let display_name = diesel_option_overwrite(&data.display_name);
49     let matrix_user_id = diesel_option_overwrite(&data.matrix_user_id);
50     let email_deref = data.email.as_deref().map(str::to_lowercase);
51     let email = diesel_option_overwrite(&email_deref);
52
53     if let Some(Some(email)) = &email {
54       let previous_email = local_user_view.local_user.email.clone().unwrap_or_default();
55       // Only send the verification email if there was an email change
56       if previous_email.ne(email) {
57         send_verification_email(&local_user_view, email, context.pool(), context.settings())
58           .await?;
59       }
60     }
61
62     // When the site requires email, make sure email is not Some(None). IE, an overwrite to a None value
63     if let Some(email) = &email {
64       if email.is_none() && site_view.local_site.require_email_verification {
65         return Err(LemmyError::from_message("email_required"));
66       }
67     }
68
69     if let Some(Some(bio)) = &bio {
70       is_valid_bio_field(bio)?;
71     }
72
73     if let Some(Some(display_name)) = &display_name {
74       is_valid_display_name(
75         display_name.trim(),
76         site_view.local_site.actor_name_max_length as usize,
77       )?;
78     }
79
80     if let Some(Some(matrix_user_id)) = &matrix_user_id {
81       is_valid_matrix_id(matrix_user_id)?;
82     }
83
84     let local_user_id = local_user_view.local_user.id;
85     let person_id = local_user_view.person.id;
86     let default_listing_type = data.default_listing_type;
87     let default_sort_type = data.default_sort_type;
88
89     let person_form = PersonUpdateForm::builder()
90       .display_name(display_name)
91       .bio(bio)
92       .matrix_user_id(matrix_user_id)
93       .bot_account(data.bot_account)
94       .avatar(avatar)
95       .banner(banner)
96       .build();
97
98     Person::update(context.pool(), person_id, &person_form)
99       .await
100       .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?;
101
102     if let Some(discussion_languages) = data.discussion_languages.clone() {
103       LocalUserLanguage::update(context.pool(), discussion_languages, local_user_id).await?;
104     }
105
106     // If generate_totp is Some(false), this will clear it out from the database.
107     let (totp_2fa_secret, totp_2fa_url) = if let Some(generate) = data.generate_totp_2fa {
108       if generate {
109         let secret = generate_totp_2fa_secret();
110         let url =
111           build_totp_2fa(&site_view.site.name, &local_user_view.person.name, &secret)?.get_url();
112         (Some(Some(secret)), Some(Some(url)))
113       } else {
114         (Some(None), Some(None))
115       }
116     } else {
117       (None, None)
118     };
119
120     let local_user_form = LocalUserUpdateForm::builder()
121       .email(email)
122       .show_avatars(data.show_avatars)
123       .show_read_posts(data.show_read_posts)
124       .show_new_post_notifs(data.show_new_post_notifs)
125       .send_notifications_to_email(data.send_notifications_to_email)
126       .show_nsfw(data.show_nsfw)
127       .show_bot_accounts(data.show_bot_accounts)
128       .show_scores(data.show_scores)
129       .default_sort_type(default_sort_type)
130       .default_listing_type(default_listing_type)
131       .theme(data.theme.clone())
132       .interface_language(data.interface_language.clone())
133       .totp_2fa_secret(totp_2fa_secret)
134       .totp_2fa_url(totp_2fa_url)
135       .build();
136
137     let local_user_res = LocalUser::update(context.pool(), local_user_id, &local_user_form).await;
138     let updated_local_user = match local_user_res {
139       Ok(u) => u,
140       Err(e) => {
141         let err_type = if e.to_string()
142           == "duplicate key value violates unique constraint \"local_user_email_key\""
143         {
144           "email_already_exists"
145         } else {
146           "user_already_exists"
147         };
148
149         return Err(LemmyError::from_error_message(e, err_type));
150       }
151     };
152
153     // Return the jwt
154     Ok(LoginResponse {
155       jwt: Some(
156         Claims::jwt(
157           updated_local_user.id.0,
158           &context.secret().jwt_secret,
159           &context.settings().hostname,
160         )?
161         .into(),
162       ),
163       verify_email_sent: false,
164       registration_created: false,
165     })
166   }
167 }