]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/save_settings.rs
Adding TOTP / 2FA to lemmy (#2741)
[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::{get_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_display_name,
25     is_valid_matrix_id,
26   },
27   ConnectionId,
28 };
29
30 #[async_trait::async_trait(?Send)]
31 impl Perform for SaveUserSettings {
32   type Response = LoginResponse;
33
34   #[tracing::instrument(skip(context, _websocket_id))]
35   async fn perform(
36     &self,
37     context: &Data<LemmyContext>,
38     _websocket_id: Option<ConnectionId>,
39   ) -> Result<LoginResponse, LemmyError> {
40     let data: &SaveUserSettings = self;
41     let local_user_view =
42       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).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       if bio.chars().count() > 300 {
71         return Err(LemmyError::from_message("bio_length_overflow"));
72       }
73     }
74
75     if let Some(Some(display_name)) = &display_name {
76       if !is_valid_display_name(
77         display_name.trim(),
78         site_view.local_site.actor_name_max_length as usize,
79       ) {
80         return Err(LemmyError::from_message("invalid_username"));
81       }
82     }
83
84     if let Some(Some(matrix_user_id)) = &matrix_user_id {
85       if !is_valid_matrix_id(matrix_user_id) {
86         return Err(LemmyError::from_message("invalid_matrix_id"));
87       }
88     }
89
90     let local_user_id = local_user_view.local_user.id;
91     let person_id = local_user_view.person.id;
92     let default_listing_type = data.default_listing_type;
93     let default_sort_type = data.default_sort_type;
94
95     let person_form = PersonUpdateForm::builder()
96       .display_name(display_name)
97       .bio(bio)
98       .matrix_user_id(matrix_user_id)
99       .bot_account(data.bot_account)
100       .avatar(avatar)
101       .banner(banner)
102       .build();
103
104     Person::update(context.pool(), person_id, &person_form)
105       .await
106       .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?;
107
108     if let Some(discussion_languages) = data.discussion_languages.clone() {
109       LocalUserLanguage::update(context.pool(), discussion_languages, local_user_id).await?;
110     }
111
112     // If generate_totp is Some(false), this will clear it out from the database.
113     let (totp_2fa_secret, totp_2fa_url) = if let Some(generate) = data.generate_totp_2fa {
114       if generate {
115         let secret = generate_totp_2fa_secret();
116         let url =
117           build_totp_2fa(&site_view.site.name, &local_user_view.person.name, &secret)?.get_url();
118         (Some(Some(secret)), Some(Some(url)))
119       } else {
120         (Some(None), Some(None))
121       }
122     } else {
123       (None, None)
124     };
125
126     let local_user_form = LocalUserUpdateForm::builder()
127       .email(email)
128       .show_avatars(data.show_avatars)
129       .show_read_posts(data.show_read_posts)
130       .show_new_post_notifs(data.show_new_post_notifs)
131       .send_notifications_to_email(data.send_notifications_to_email)
132       .show_nsfw(data.show_nsfw)
133       .show_bot_accounts(data.show_bot_accounts)
134       .show_scores(data.show_scores)
135       .default_sort_type(default_sort_type)
136       .default_listing_type(default_listing_type)
137       .theme(data.theme.clone())
138       .interface_language(data.interface_language.clone())
139       .totp_2fa_secret(totp_2fa_secret)
140       .totp_2fa_url(totp_2fa_url)
141       .build();
142
143     let local_user_res = LocalUser::update(context.pool(), local_user_id, &local_user_form).await;
144     let updated_local_user = match local_user_res {
145       Ok(u) => u,
146       Err(e) => {
147         let err_type = if e.to_string()
148           == "duplicate key value violates unique constraint \"local_user_email_key\""
149         {
150           "email_already_exists"
151         } else {
152           "user_already_exists"
153         };
154
155         return Err(LemmyError::from_error_message(e, err_type));
156       }
157     };
158
159     // Return the jwt
160     Ok(LoginResponse {
161       jwt: Some(
162         Claims::jwt(
163           updated_local_user.id.0,
164           &context.secret().jwt_secret,
165           &context.settings().hostname,
166         )?
167         .into(),
168       ),
169       verify_email_sent: false,
170       registration_created: false,
171     })
172   }
173 }