]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/save_settings.rs
Convert emails to lowercase (fixes #2462) (#2463)
[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   person::{LoginResponse, SaveUserSettings},
5   utils::{blocking, get_local_user_view_from_jwt, send_verification_email},
6 };
7 use lemmy_db_schema::{
8   source::{
9     local_user::{LocalUser, LocalUserForm},
10     local_user_language::LocalUserLanguage,
11     person::{Person, PersonForm},
12     site::Site,
13   },
14   traits::Crud,
15   utils::{diesel_option_overwrite, diesel_option_overwrite_to_url, naive_now},
16 };
17 use lemmy_utils::{
18   claims::Claims,
19   error::LemmyError,
20   utils::{is_valid_display_name, is_valid_matrix_id},
21   ConnectionId,
22 };
23 use lemmy_websocket::LemmyContext;
24
25 #[async_trait::async_trait(?Send)]
26 impl Perform for SaveUserSettings {
27   type Response = LoginResponse;
28
29   #[tracing::instrument(skip(context, _websocket_id))]
30   async fn perform(
31     &self,
32     context: &Data<LemmyContext>,
33     _websocket_id: Option<ConnectionId>,
34   ) -> Result<LoginResponse, LemmyError> {
35     let data: &SaveUserSettings = self;
36     let local_user_view =
37       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
38
39     let avatar = diesel_option_overwrite_to_url(&data.avatar)?;
40     let banner = diesel_option_overwrite_to_url(&data.banner)?;
41     let bio = diesel_option_overwrite(&data.bio);
42     let display_name = diesel_option_overwrite(&data.display_name);
43     let matrix_user_id = diesel_option_overwrite(&data.matrix_user_id);
44     let bot_account = data.bot_account;
45     let email_deref = data.email.as_deref().map(|e| e.to_lowercase());
46     let email = diesel_option_overwrite(&email_deref);
47
48     if let Some(Some(email)) = &email {
49       let previous_email = local_user_view.local_user.email.clone().unwrap_or_default();
50       // Only send the verification email if there was an email change
51       if previous_email.ne(email) {
52         send_verification_email(&local_user_view, email, context.pool(), context.settings())
53           .await?;
54       }
55     }
56
57     // When the site requires email, make sure email is not Some(None). IE, an overwrite to a None value
58     if let Some(email) = &email {
59       let site_fut = blocking(context.pool(), Site::read_local_site);
60       if email.is_none() && site_fut.await??.require_email_verification {
61         return Err(LemmyError::from_message("email_required"));
62       }
63     }
64
65     if let Some(Some(bio)) = &bio {
66       if bio.chars().count() > 300 {
67         return Err(LemmyError::from_message("bio_length_overflow"));
68       }
69     }
70
71     if let Some(Some(display_name)) = &display_name {
72       if !is_valid_display_name(
73         display_name.trim(),
74         context.settings().actor_name_max_length,
75       ) {
76         return Err(LemmyError::from_message("invalid_username"));
77       }
78     }
79
80     if let Some(Some(matrix_user_id)) = &matrix_user_id {
81       if !is_valid_matrix_id(matrix_user_id) {
82         return Err(LemmyError::from_message("invalid_matrix_id"));
83       }
84     }
85
86     let local_user_id = local_user_view.local_user.id;
87     let person_id = local_user_view.person.id;
88     let default_listing_type = data.default_listing_type;
89     let default_sort_type = data.default_sort_type;
90     let password_encrypted = local_user_view.local_user.password_encrypted;
91     let public_key = Some(local_user_view.person.public_key);
92
93     let person_form = PersonForm {
94       name: local_user_view.person.name,
95       avatar,
96       banner,
97       inbox_url: None,
98       display_name,
99       published: None,
100       updated: Some(naive_now()),
101       banned: None,
102       deleted: None,
103       actor_id: None,
104       bio,
105       local: None,
106       admin: None,
107       private_key: None,
108       public_key,
109       last_refreshed_at: None,
110       shared_inbox_url: None,
111       matrix_user_id,
112       bot_account,
113       ban_expires: None,
114     };
115
116     blocking(context.pool(), move |conn| {
117       Person::update(conn, person_id, &person_form)
118     })
119     .await?
120     .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?;
121
122     if let Some(discussion_languages) = data.discussion_languages.clone() {
123       // An empty array is a "clear" / set all languages
124       let languages = if discussion_languages.is_empty() {
125         None
126       } else {
127         Some(discussion_languages)
128       };
129
130       blocking(context.pool(), move |conn| {
131         LocalUserLanguage::update_user_languages(conn, languages, local_user_id)
132       })
133       .await??;
134     }
135
136     let local_user_form = LocalUserForm {
137       person_id: Some(person_id),
138       email,
139       password_encrypted: Some(password_encrypted),
140       show_nsfw: data.show_nsfw,
141       show_bot_accounts: data.show_bot_accounts,
142       show_scores: data.show_scores,
143       theme: data.theme.to_owned(),
144       default_sort_type,
145       default_listing_type,
146       interface_language: data.interface_language.to_owned(),
147       show_avatars: data.show_avatars,
148       show_read_posts: data.show_read_posts,
149       show_new_post_notifs: data.show_new_post_notifs,
150       send_notifications_to_email: data.send_notifications_to_email,
151       email_verified: None,
152       accepted_application: None,
153     };
154
155     let local_user_res = blocking(context.pool(), move |conn| {
156       LocalUser::update(conn, local_user_id, &local_user_form)
157     })
158     .await?;
159     let updated_local_user = match local_user_res {
160       Ok(u) => u,
161       Err(e) => {
162         let err_type = if e.to_string()
163           == "duplicate key value violates unique constraint \"local_user_email_key\""
164         {
165           "email_already_exists"
166         } else {
167           "user_already_exists"
168         };
169
170         return Err(LemmyError::from_error_message(e, err_type));
171       }
172     };
173
174     // Return the jwt
175     Ok(LoginResponse {
176       jwt: Some(
177         Claims::jwt(
178           updated_local_user.id.0,
179           &context.secret().jwt_secret,
180           &context.settings().hostname,
181         )?
182         .into(),
183       ),
184       verify_email_sent: false,
185       registration_created: false,
186     })
187   }
188 }