]> Untitled Git - lemmy.git/blob - crates/api_crud/src/user/create.rs
Rework error handling (fixes #1714) (#2135)
[lemmy.git] / crates / api_crud / src / user / create.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   blocking,
5   honeypot_check,
6   password_length_check,
7   person::*,
8   send_verification_email,
9 };
10 use lemmy_apub::{
11   generate_followers_url,
12   generate_inbox_url,
13   generate_local_apub_endpoint,
14   generate_shared_inbox_url,
15   EndpointType,
16 };
17 use lemmy_db_schema::{
18   newtypes::CommunityId,
19   source::{
20     community::{
21       Community,
22       CommunityFollower,
23       CommunityFollowerForm,
24       CommunityForm,
25       CommunityModerator,
26       CommunityModeratorForm,
27     },
28     local_user::{LocalUser, LocalUserForm},
29     person::{Person, PersonForm},
30     registration_application::{RegistrationApplication, RegistrationApplicationForm},
31     site::Site,
32   },
33   traits::{Crud, Followable, Joinable},
34 };
35 use lemmy_db_views_actor::person_view::PersonViewSafe;
36 use lemmy_utils::{
37   apub::generate_actor_keypair,
38   claims::Claims,
39   utils::{check_slurs, is_valid_actor_name},
40   ConnectionId,
41   LemmyError,
42 };
43 use lemmy_websocket::{messages::CheckCaptcha, LemmyContext};
44
45 #[async_trait::async_trait(?Send)]
46 impl PerformCrud for Register {
47   type Response = LoginResponse;
48
49   #[tracing::instrument(skip(self, context, _websocket_id))]
50   async fn perform(
51     &self,
52     context: &Data<LemmyContext>,
53     _websocket_id: Option<ConnectionId>,
54   ) -> Result<LoginResponse, LemmyError> {
55     let data: &Register = self;
56
57     // no email verification, or applications if the site is not setup yet
58     let (mut email_verification, mut require_application) = (false, false);
59
60     // Make sure site has open registration
61     if let Ok(site) = blocking(context.pool(), Site::read_local_site).await? {
62       if !site.open_registration {
63         return Err(LemmyError::from_message("registration_closed"));
64       }
65       email_verification = site.require_email_verification;
66       require_application = site.require_application;
67     }
68
69     password_length_check(&data.password)?;
70     honeypot_check(&data.honeypot)?;
71
72     if email_verification && data.email.is_none() {
73       return Err(LemmyError::from_message("email_required"));
74     }
75
76     if require_application && data.answer.is_none() {
77       return Err(LemmyError::from_message(
78         "registration_application_answer_required",
79       ));
80     }
81
82     // Make sure passwords match
83     if data.password != data.password_verify {
84       return Err(LemmyError::from_message("passwords_dont_match"));
85     }
86
87     // Check if there are admins. False if admins exist
88     let no_admins = blocking(context.pool(), move |conn| {
89       PersonViewSafe::admins(conn).map(|a| a.is_empty())
90     })
91     .await??;
92
93     // If its not the admin, check the captcha
94     if !no_admins && context.settings().captcha.enabled {
95       let check = context
96         .chat_server()
97         .send(CheckCaptcha {
98           uuid: data
99             .captcha_uuid
100             .to_owned()
101             .unwrap_or_else(|| "".to_string()),
102           answer: data
103             .captcha_answer
104             .to_owned()
105             .unwrap_or_else(|| "".to_string()),
106         })
107         .await?;
108       if !check {
109         return Err(LemmyError::from_message("captcha_incorrect"));
110       }
111     }
112
113     check_slurs(&data.username, &context.settings().slur_regex())?;
114
115     let actor_keypair = generate_actor_keypair()?;
116     if !is_valid_actor_name(&data.username, context.settings().actor_name_max_length) {
117       return Err(LemmyError::from_message("invalid_username"));
118     }
119     let actor_id = generate_local_apub_endpoint(
120       EndpointType::Person,
121       &data.username,
122       &context.settings().get_protocol_and_hostname(),
123     )?;
124
125     // We have to create both a person, and local_user
126
127     // Register the new person
128     let person_form = PersonForm {
129       name: data.username.to_owned(),
130       actor_id: Some(actor_id.clone()),
131       private_key: Some(Some(actor_keypair.private_key)),
132       public_key: actor_keypair.public_key,
133       inbox_url: Some(generate_inbox_url(&actor_id)?),
134       shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
135       admin: Some(no_admins),
136       ..PersonForm::default()
137     };
138
139     // insert the person
140     let inserted_person = blocking(context.pool(), move |conn| {
141       Person::create(conn, &person_form)
142     })
143     .await?
144     .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?;
145
146     // Create the local user
147     let local_user_form = LocalUserForm {
148       person_id: Some(inserted_person.id),
149       email: Some(data.email.as_deref().map(|s| s.to_owned())),
150       password_encrypted: Some(data.password.to_string()),
151       show_nsfw: Some(data.show_nsfw),
152       email_verified: Some(false),
153       ..LocalUserForm::default()
154     };
155
156     let inserted_local_user = match blocking(context.pool(), move |conn| {
157       LocalUser::register(conn, &local_user_form)
158     })
159     .await?
160     {
161       Ok(lu) => lu,
162       Err(e) => {
163         let err_type = if e.to_string()
164           == "duplicate key value violates unique constraint \"local_user_email_key\""
165         {
166           "email_already_exists"
167         } else {
168           "user_already_exists"
169         };
170
171         // If the local user creation errored, then delete that person
172         blocking(context.pool(), move |conn| {
173           Person::delete(conn, inserted_person.id)
174         })
175         .await??;
176
177         return Err(LemmyError::from_error_message(e, err_type));
178       }
179     };
180
181     if require_application {
182       // Create the registration application
183       let form = RegistrationApplicationForm {
184         local_user_id: Some(inserted_local_user.id),
185         // We already made sure answer was not null above
186         answer: data.answer.to_owned(),
187         ..RegistrationApplicationForm::default()
188       };
189
190       blocking(context.pool(), move |conn| {
191         RegistrationApplication::create(conn, &form)
192       })
193       .await??;
194     }
195
196     let main_community_keypair = generate_actor_keypair()?;
197
198     // Create the main community if it doesn't exist
199     let protocol_and_hostname = context.settings().get_protocol_and_hostname();
200     let main_community = match blocking(context.pool(), move |conn| {
201       Community::read(conn, CommunityId(2))
202     })
203     .await?
204     {
205       Ok(c) => c,
206       Err(_e) => {
207         let default_community_name = "main";
208         let actor_id = generate_local_apub_endpoint(
209           EndpointType::Community,
210           default_community_name,
211           &protocol_and_hostname,
212         )?;
213         let community_form = CommunityForm {
214           name: default_community_name.to_string(),
215           title: "The Default Community".to_string(),
216           description: Some("The Default Community".to_string()),
217           actor_id: Some(actor_id.to_owned()),
218           private_key: Some(Some(main_community_keypair.private_key)),
219           public_key: main_community_keypair.public_key,
220           followers_url: Some(generate_followers_url(&actor_id)?),
221           inbox_url: Some(generate_inbox_url(&actor_id)?),
222           shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
223           ..CommunityForm::default()
224         };
225         blocking(context.pool(), move |conn| {
226           Community::create(conn, &community_form)
227         })
228         .await??
229       }
230     };
231
232     // Sign them up for main community no matter what
233     let community_follower_form = CommunityFollowerForm {
234       community_id: main_community.id,
235       person_id: inserted_person.id,
236       pending: false,
237     };
238
239     let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
240     blocking(context.pool(), follow)
241       .await?
242       .map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?;
243
244     // If its an admin, add them as a mod and follower to main
245     if no_admins {
246       let community_moderator_form = CommunityModeratorForm {
247         community_id: main_community.id,
248         person_id: inserted_person.id,
249       };
250
251       let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
252       blocking(context.pool(), join)
253         .await?
254         .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
255     }
256
257     let mut login_response = LoginResponse {
258       jwt: None,
259       registration_created: false,
260       verify_email_sent: false,
261     };
262
263     // Log the user in directly if email verification and application aren't required
264     if !require_application && !email_verification {
265       login_response.jwt = Some(
266         Claims::jwt(
267           inserted_local_user.id.0,
268           &context.secret().jwt_secret,
269           &context.settings().hostname,
270         )?
271         .into(),
272       );
273     } else {
274       if email_verification {
275         send_verification_email(
276           inserted_local_user.id,
277           // we check at the beginning of this method that email is set
278           &inserted_local_user.email.expect("email was provided"),
279           &inserted_person.name,
280           context.pool(),
281           &context.settings(),
282         )
283         .await?;
284         login_response.verify_email_sent = true;
285       }
286
287       if require_application {
288         login_response.registration_created = true;
289       }
290     }
291
292     Ok(login_response)
293   }
294 }