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