]> Untitled Git - lemmy.git/blob - crates/api_crud/src/user/create.rs
a6979382a1d8aafdd3a89e72a1fb7a617ed140a8
[lemmy.git] / crates / api_crud / src / user / create.rs
1 use crate::PerformCrud;
2 use activitypub_federation::core::signatures::generate_actor_keypair;
3 use actix_web::web::Data;
4 use lemmy_api_common::{
5   context::LemmyContext,
6   person::{LoginResponse, Register},
7   utils::{
8     generate_inbox_url,
9     generate_local_apub_endpoint,
10     generate_shared_inbox_url,
11     honeypot_check,
12     local_site_to_slur_regex,
13     password_length_check,
14     send_new_applicant_email_to_admins,
15     send_verification_email,
16     EndpointType,
17   },
18 };
19 use lemmy_db_schema::{
20   aggregates::structs::PersonAggregates,
21   source::{
22     local_site::RegistrationMode,
23     local_user::{LocalUser, LocalUserInsertForm},
24     person::{Person, PersonInsertForm},
25     registration_application::{RegistrationApplication, RegistrationApplicationInsertForm},
26   },
27   traits::Crud,
28 };
29 use lemmy_db_views::structs::{LocalUserView, SiteView};
30 use lemmy_utils::{
31   claims::Claims,
32   error::LemmyError,
33   utils::{check_slurs, check_slurs_opt, is_valid_actor_name},
34   ConnectionId,
35 };
36
37 #[async_trait::async_trait(?Send)]
38 impl PerformCrud for Register {
39   type Response = LoginResponse;
40
41   #[tracing::instrument(skip(self, context, _websocket_id))]
42   async fn perform(
43     &self,
44     context: &Data<LemmyContext>,
45     _websocket_id: Option<ConnectionId>,
46   ) -> Result<LoginResponse, LemmyError> {
47     let data: &Register = self;
48
49     let site_view = SiteView::read_local(context.pool()).await?;
50     let local_site = site_view.local_site;
51     let require_registration_application =
52       local_site.registration_mode == RegistrationMode::RequireApplication;
53
54     if local_site.registration_mode == RegistrationMode::Closed {
55       return Err(LemmyError::from_message("registration_closed"));
56     }
57
58     password_length_check(&data.password)?;
59     honeypot_check(&data.honeypot)?;
60
61     if local_site.require_email_verification && data.email.is_none() {
62       return Err(LemmyError::from_message("email_required"));
63     }
64
65     if local_site.site_setup && require_registration_application && data.answer.is_none() {
66       return Err(LemmyError::from_message(
67         "registration_application_answer_required",
68       ));
69     }
70
71     // Make sure passwords match
72     if data.password != data.password_verify {
73       return Err(LemmyError::from_message("passwords_dont_match"));
74     }
75
76     // If the site is set up, check the captcha
77     if local_site.site_setup && local_site.captcha_enabled {
78       let check = context.chat_server().check_captcha(
79         data.captcha_uuid.clone().unwrap_or_default(),
80         data.captcha_answer.clone().unwrap_or_default(),
81       )?;
82       if !check {
83         return Err(LemmyError::from_message("captcha_incorrect"));
84       }
85     }
86
87     let slur_regex = local_site_to_slur_regex(&local_site);
88     check_slurs(&data.username, &slur_regex)?;
89     check_slurs_opt(&data.answer, &slur_regex)?;
90
91     let actor_keypair = generate_actor_keypair()?;
92     if !is_valid_actor_name(&data.username, local_site.actor_name_max_length as usize) {
93       return Err(LemmyError::from_message("invalid_username"));
94     }
95     let actor_id = generate_local_apub_endpoint(
96       EndpointType::Person,
97       &data.username,
98       &context.settings().get_protocol_and_hostname(),
99     )?;
100
101     // We have to create both a person, and local_user
102
103     // Register the new person
104     let person_form = PersonInsertForm::builder()
105       .name(data.username.clone())
106       .actor_id(Some(actor_id.clone()))
107       .private_key(Some(actor_keypair.private_key))
108       .public_key(actor_keypair.public_key)
109       .inbox_url(Some(generate_inbox_url(&actor_id)?))
110       .shared_inbox_url(Some(generate_shared_inbox_url(&actor_id)?))
111       // If its the initial site setup, they are an admin
112       .admin(Some(!local_site.site_setup))
113       .instance_id(site_view.site.instance_id)
114       .build();
115
116     // insert the person
117     let inserted_person = Person::create(context.pool(), &person_form)
118       .await
119       .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?;
120
121     // Create the local user
122     let local_user_form = LocalUserInsertForm::builder()
123       .person_id(inserted_person.id)
124       .email(data.email.as_deref().map(str::to_lowercase))
125       .password_encrypted(data.password.to_string())
126       .show_nsfw(Some(data.show_nsfw))
127       .build();
128
129     let inserted_local_user = match LocalUser::create(context.pool(), &local_user_form).await {
130       Ok(lu) => lu,
131       Err(e) => {
132         let err_type = if e.to_string()
133           == "duplicate key value violates unique constraint \"local_user_email_key\""
134         {
135           "email_already_exists"
136         } else {
137           "user_already_exists"
138         };
139
140         // If the local user creation errored, then delete that person
141         Person::delete(context.pool(), inserted_person.id).await?;
142
143         return Err(LemmyError::from_error_message(e, err_type));
144       }
145     };
146
147     if local_site.site_setup && require_registration_application {
148       // Create the registration application
149       let form = RegistrationApplicationInsertForm {
150         local_user_id: inserted_local_user.id,
151         // We already made sure answer was not null above
152         answer: data.answer.clone().expect("must have an answer"),
153       };
154
155       RegistrationApplication::create(context.pool(), &form).await?;
156     }
157
158     // Email the admins
159     if local_site.application_email_admins {
160       send_new_applicant_email_to_admins(&data.username, context.pool(), context.settings())
161         .await?;
162     }
163
164     let mut login_response = LoginResponse {
165       jwt: None,
166       registration_created: false,
167       verify_email_sent: false,
168     };
169
170     // Log the user in directly if the site is not setup, or email verification and application aren't required
171     if !local_site.site_setup
172       || (!require_registration_application && !local_site.require_email_verification)
173     {
174       login_response.jwt = Some(
175         Claims::jwt(
176           inserted_local_user.id.0,
177           &context.secret().jwt_secret,
178           &context.settings().hostname,
179         )?
180         .into(),
181       );
182     } else {
183       if local_site.require_email_verification {
184         let local_user_view = LocalUserView {
185           local_user: inserted_local_user,
186           person: inserted_person,
187           counts: PersonAggregates::default(),
188         };
189         // we check at the beginning of this method that email is set
190         let email = local_user_view
191           .local_user
192           .email
193           .clone()
194           .expect("email was provided");
195
196         send_verification_email(&local_user_view, &email, context.pool(), context.settings())
197           .await?;
198         login_response.verify_email_sent = true;
199       }
200
201       if require_registration_application {
202         login_response.registration_created = true;
203       }
204     }
205
206     Ok(login_response)
207   }
208 }