]> Untitled Git - lemmy.git/blob - crates/api_crud/src/user/create.rs
06b576e51a46c81d0aec209a8fd56cb58c47bd86
[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(LemmyError::from)
145     .map_err(|e| e.with_message("user_already_exists"))?;
146
147     // Create the local user
148     let local_user_form = LocalUserForm {
149       person_id: Some(inserted_person.id),
150       email: Some(data.email.as_deref().map(|s| s.to_owned())),
151       password_encrypted: Some(data.password.to_string()),
152       show_nsfw: Some(data.show_nsfw),
153       email_verified: Some(false),
154       ..LocalUserForm::default()
155     };
156
157     let inserted_local_user = match blocking(context.pool(), move |conn| {
158       LocalUser::register(conn, &local_user_form)
159     })
160     .await?
161     {
162       Ok(lu) => lu,
163       Err(e) => {
164         let err_type = if e.to_string()
165           == "duplicate key value violates unique constraint \"local_user_email_key\""
166         {
167           "email_already_exists"
168         } else {
169           "user_already_exists"
170         };
171
172         // If the local user creation errored, then delete that person
173         blocking(context.pool(), move |conn| {
174           Person::delete(conn, inserted_person.id)
175         })
176         .await??;
177
178         return Err(LemmyError::from(e).with_message(err_type));
179       }
180     };
181
182     if require_application {
183       // Create the registration application
184       let form = RegistrationApplicationForm {
185         local_user_id: Some(inserted_local_user.id),
186         // We already made sure answer was not null above
187         answer: data.answer.to_owned(),
188         ..RegistrationApplicationForm::default()
189       };
190
191       blocking(context.pool(), move |conn| {
192         RegistrationApplication::create(conn, &form)
193       })
194       .await??;
195     }
196
197     let main_community_keypair = generate_actor_keypair()?;
198
199     // Create the main community if it doesn't exist
200     let protocol_and_hostname = context.settings().get_protocol_and_hostname();
201     let main_community = match blocking(context.pool(), move |conn| {
202       Community::read(conn, CommunityId(2))
203     })
204     .await?
205     {
206       Ok(c) => c,
207       Err(_e) => {
208         let default_community_name = "main";
209         let actor_id = generate_local_apub_endpoint(
210           EndpointType::Community,
211           default_community_name,
212           &protocol_and_hostname,
213         )?;
214         let community_form = CommunityForm {
215           name: default_community_name.to_string(),
216           title: "The Default Community".to_string(),
217           description: Some("The Default Community".to_string()),
218           actor_id: Some(actor_id.to_owned()),
219           private_key: Some(Some(main_community_keypair.private_key)),
220           public_key: main_community_keypair.public_key,
221           followers_url: Some(generate_followers_url(&actor_id)?),
222           inbox_url: Some(generate_inbox_url(&actor_id)?),
223           shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
224           ..CommunityForm::default()
225         };
226         blocking(context.pool(), move |conn| {
227           Community::create(conn, &community_form)
228         })
229         .await??
230       }
231     };
232
233     // Sign them up for main community no matter what
234     let community_follower_form = CommunityFollowerForm {
235       community_id: main_community.id,
236       person_id: inserted_person.id,
237       pending: false,
238     };
239
240     let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
241     blocking(context.pool(), follow)
242       .await?
243       .map_err(LemmyError::from)
244       .map_err(|e| e.with_message("community_follower_already_exists"))?;
245
246     // If its an admin, add them as a mod and follower to main
247     if no_admins {
248       let community_moderator_form = CommunityModeratorForm {
249         community_id: main_community.id,
250         person_id: inserted_person.id,
251       };
252
253       let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
254       blocking(context.pool(), join)
255         .await?
256         .map_err(LemmyError::from)
257         .map_err(|e| e.with_message("community_moderator_already_exists"))?;
258     }
259
260     let mut login_response = LoginResponse {
261       jwt: None,
262       registration_created: false,
263       verify_email_sent: false,
264     };
265
266     // Log the user in directly if email verification and application aren't required
267     if !require_application && !email_verification {
268       login_response.jwt = Some(
269         Claims::jwt(
270           inserted_local_user.id.0,
271           &context.secret().jwt_secret,
272           &context.settings().hostname,
273         )?
274         .into(),
275       );
276     } else {
277       if email_verification {
278         send_verification_email(
279           inserted_local_user.id,
280           // we check at the beginning of this method that email is set
281           &inserted_local_user.email.expect("email was provided"),
282           &inserted_person.name,
283           context.pool(),
284           &context.settings(),
285         )
286         .await?;
287         login_response.verify_email_sent = true;
288       }
289
290       if require_application {
291         login_response.registration_created = true;
292       }
293     }
294
295     Ok(login_response)
296   }
297 }