]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/save_settings.rs
Error enum fixed (#3487)
[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, LemmyErrorExt, LemmyErrorType},
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 };
29
30 #[async_trait::async_trait(?Send)]
31 impl Perform for SaveUserSettings {
32   type Response = LoginResponse;
33
34   #[tracing::instrument(skip(context))]
35   async fn perform(&self, context: &Data<LemmyContext>) -> Result<LoginResponse, LemmyError> {
36     let data: &SaveUserSettings = self;
37     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
38     let site_view = SiteView::read_local(context.pool()).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 email_deref = data.email.as_deref().map(str::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       if email.is_none() && site_view.local_site.require_email_verification {
60         return Err(LemmyErrorType::EmailRequired)?;
61       }
62     }
63
64     if let Some(Some(bio)) = &bio {
65       is_valid_bio_field(bio)?;
66     }
67
68     if let Some(Some(display_name)) = &display_name {
69       is_valid_display_name(
70         display_name.trim(),
71         site_view.local_site.actor_name_max_length as usize,
72       )?;
73     }
74
75     if let Some(Some(matrix_user_id)) = &matrix_user_id {
76       is_valid_matrix_id(matrix_user_id)?;
77     }
78
79     let local_user_id = local_user_view.local_user.id;
80     let person_id = local_user_view.person.id;
81     let default_listing_type = data.default_listing_type;
82     let default_sort_type = data.default_sort_type;
83
84     let person_form = PersonUpdateForm::builder()
85       .display_name(display_name)
86       .bio(bio)
87       .matrix_user_id(matrix_user_id)
88       .bot_account(data.bot_account)
89       .avatar(avatar)
90       .banner(banner)
91       .build();
92
93     Person::update(context.pool(), person_id, &person_form)
94       .await
95       .with_lemmy_type(LemmyErrorType::UserAlreadyExists)?;
96
97     if let Some(discussion_languages) = data.discussion_languages.clone() {
98       LocalUserLanguage::update(context.pool(), discussion_languages, local_user_id).await?;
99     }
100
101     // If generate_totp is Some(false), this will clear it out from the database.
102     let (totp_2fa_secret, totp_2fa_url) = if let Some(generate) = data.generate_totp_2fa {
103       if generate {
104         let secret = generate_totp_2fa_secret();
105         let url =
106           build_totp_2fa(&site_view.site.name, &local_user_view.person.name, &secret)?.get_url();
107         (Some(Some(secret)), Some(Some(url)))
108       } else {
109         (Some(None), Some(None))
110       }
111     } else {
112       (None, None)
113     };
114
115     let local_user_form = LocalUserUpdateForm::builder()
116       .email(email)
117       .show_avatars(data.show_avatars)
118       .show_read_posts(data.show_read_posts)
119       .show_new_post_notifs(data.show_new_post_notifs)
120       .send_notifications_to_email(data.send_notifications_to_email)
121       .show_nsfw(data.show_nsfw)
122       .show_bot_accounts(data.show_bot_accounts)
123       .show_scores(data.show_scores)
124       .default_sort_type(default_sort_type)
125       .default_listing_type(default_listing_type)
126       .theme(data.theme.clone())
127       .interface_language(data.interface_language.clone())
128       .totp_2fa_secret(totp_2fa_secret)
129       .totp_2fa_url(totp_2fa_url)
130       .open_links_in_new_tab(data.open_links_in_new_tab)
131       .build();
132
133     let local_user_res = LocalUser::update(context.pool(), local_user_id, &local_user_form).await;
134     let updated_local_user = match local_user_res {
135       Ok(u) => u,
136       Err(e) => {
137         let err_type = if e.to_string()
138           == "duplicate key value violates unique constraint \"local_user_email_key\""
139         {
140           LemmyErrorType::EmailAlreadyExists
141         } else {
142           LemmyErrorType::UserAlreadyExists
143         };
144
145         return Err(e).with_lemmy_type(err_type);
146       }
147     };
148
149     // Return the jwt
150     Ok(LoginResponse {
151       jwt: Some(
152         Claims::jwt(
153           updated_local_user.id.0,
154           &context.secret().jwt_secret,
155           &context.settings().hostname,
156         )?
157         .into(),
158       ),
159       verify_email_sent: false,
160       registration_created: false,
161     })
162   }
163 }