]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/save_settings.rs
Moving settings to Database. (#2492)
[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     actor_language::LocalUserLanguage,
10     local_site::LocalSite,
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_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     let local_site = blocking(context.pool(), LocalSite::read).await??;
39
40     let avatar = diesel_option_overwrite_to_url(&data.avatar)?;
41     let banner = diesel_option_overwrite_to_url(&data.banner)?;
42     let bio = diesel_option_overwrite(&data.bio);
43     let display_name = diesel_option_overwrite(&data.display_name);
44     let matrix_user_id = diesel_option_overwrite(&data.matrix_user_id);
45     let bot_account = data.bot_account;
46     let email_deref = data.email.as_deref().map(|e| e.to_lowercase());
47     let email = diesel_option_overwrite(&email_deref);
48
49     if let Some(Some(email)) = &email {
50       let previous_email = local_user_view.local_user.email.clone().unwrap_or_default();
51       // Only send the verification email if there was an email change
52       if previous_email.ne(email) {
53         send_verification_email(&local_user_view, email, context.pool(), context.settings())
54           .await?;
55       }
56     }
57
58     // When the site requires email, make sure email is not Some(None). IE, an overwrite to a None value
59     if let Some(email) = &email {
60       if email.is_none() && local_site.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         local_site.actor_name_max_length as usize,
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
91     let person_form = PersonUpdateForm::builder()
92       .display_name(display_name)
93       .bio(bio)
94       .matrix_user_id(matrix_user_id)
95       .bot_account(bot_account)
96       .avatar(avatar)
97       .banner(banner)
98       .build();
99
100     blocking(context.pool(), move |conn| {
101       Person::update(conn, person_id, &person_form)
102     })
103     .await?
104     .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?;
105
106     if let Some(discussion_languages) = data.discussion_languages.clone() {
107       blocking(context.pool(), move |conn| {
108         LocalUserLanguage::update(conn, discussion_languages, local_user_id)
109       })
110       .await??;
111     }
112
113     let local_user_form = LocalUserUpdateForm::builder()
114       .email(email)
115       .show_avatars(data.show_avatars)
116       .show_read_posts(data.show_read_posts)
117       .show_new_post_notifs(data.show_new_post_notifs)
118       .send_notifications_to_email(data.send_notifications_to_email)
119       .show_nsfw(data.show_nsfw)
120       .show_bot_accounts(data.show_bot_accounts)
121       .show_scores(data.show_scores)
122       .default_sort_type(default_sort_type)
123       .default_listing_type(default_listing_type)
124       .theme(data.theme.to_owned())
125       .interface_language(data.interface_language.to_owned())
126       .build();
127
128     let local_user_res = blocking(context.pool(), move |conn| {
129       LocalUser::update(conn, local_user_id, &local_user_form)
130     })
131     .await?;
132     let updated_local_user = match local_user_res {
133       Ok(u) => u,
134       Err(e) => {
135         let err_type = if e.to_string()
136           == "duplicate key value violates unique constraint \"local_user_email_key\""
137         {
138           "email_already_exists"
139         } else {
140           "user_already_exists"
141         };
142
143         return Err(LemmyError::from_error_message(e, err_type));
144       }
145     };
146
147     // Return the jwt
148     Ok(LoginResponse {
149       jwt: Some(
150         Claims::jwt(
151           updated_local_user.id.0,
152           &context.secret().jwt_secret,
153           &context.settings().hostname,
154         )?
155         .into(),
156       ),
157       verify_email_sent: false,
158       registration_created: false,
159     })
160   }
161 }