]> Untitled Git - lemmy.git/blob - crates/api_crud/src/user/create.rs
34b3b69e47004d154d9018662d570314879a51d4
[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   websocket::messages::CheckCaptcha,
19 };
20 use lemmy_db_schema::{
21   aggregates::structs::PersonAggregates,
22   source::{
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
52     if !local_site.open_registration {
53       return Err(LemmyError::from_message("registration_closed"));
54     }
55
56     password_length_check(&data.password)?;
57     honeypot_check(&data.honeypot)?;
58
59     if local_site.require_email_verification && data.email.is_none() {
60       return Err(LemmyError::from_message("email_required"));
61     }
62
63     if local_site.site_setup && local_site.require_application && data.answer.is_none() {
64       return Err(LemmyError::from_message(
65         "registration_application_answer_required",
66       ));
67     }
68
69     // Make sure passwords match
70     if data.password != data.password_verify {
71       return Err(LemmyError::from_message("passwords_dont_match"));
72     }
73
74     // If the site is set up, check the captcha
75     if local_site.site_setup && local_site.captcha_enabled {
76       let check = context
77         .chat_server()
78         .send(CheckCaptcha {
79           uuid: data.captcha_uuid.clone().unwrap_or_default(),
80           answer: data.captcha_answer.clone().unwrap_or_default(),
81         })
82         .await?;
83       if !check {
84         return Err(LemmyError::from_message("captcha_incorrect"));
85       }
86     }
87
88     let slur_regex = local_site_to_slur_regex(&local_site);
89     check_slurs(&data.username, &slur_regex)?;
90     check_slurs_opt(&data.answer, &slur_regex)?;
91
92     let actor_keypair = generate_actor_keypair()?;
93     if !is_valid_actor_name(&data.username, local_site.actor_name_max_length as usize) {
94       return Err(LemmyError::from_message("invalid_username"));
95     }
96     let actor_id = generate_local_apub_endpoint(
97       EndpointType::Person,
98       &data.username,
99       &context.settings().get_protocol_and_hostname(),
100     )?;
101
102     // We have to create both a person, and local_user
103
104     // Register the new person
105     let person_form = PersonInsertForm::builder()
106       .name(data.username.clone())
107       .actor_id(Some(actor_id.clone()))
108       .private_key(Some(actor_keypair.private_key))
109       .public_key(actor_keypair.public_key)
110       .inbox_url(Some(generate_inbox_url(&actor_id)?))
111       .shared_inbox_url(Some(generate_shared_inbox_url(&actor_id)?))
112       // If its the initial site setup, they are an admin
113       .admin(Some(!local_site.site_setup))
114       .instance_id(site_view.site.instance_id)
115       .build();
116
117     // insert the person
118     let inserted_person = Person::create(context.pool(), &person_form)
119       .await
120       .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?;
121
122     // Create the local user
123     let local_user_form = LocalUserInsertForm::builder()
124       .person_id(inserted_person.id)
125       .email(data.email.as_deref().map(str::to_lowercase))
126       .password_encrypted(data.password.to_string())
127       .show_nsfw(Some(data.show_nsfw))
128       .build();
129
130     let inserted_local_user = match LocalUser::create(context.pool(), &local_user_form).await {
131       Ok(lu) => lu,
132       Err(e) => {
133         let err_type = if e.to_string()
134           == "duplicate key value violates unique constraint \"local_user_email_key\""
135         {
136           "email_already_exists"
137         } else {
138           "user_already_exists"
139         };
140
141         // If the local user creation errored, then delete that person
142         Person::delete(context.pool(), inserted_person.id).await?;
143
144         return Err(LemmyError::from_error_message(e, err_type));
145       }
146     };
147
148     if local_site.site_setup && local_site.require_application {
149       // Create the registration application
150       let form = RegistrationApplicationInsertForm {
151         local_user_id: inserted_local_user.id,
152         // We already made sure answer was not null above
153         answer: data.answer.clone().expect("must have an answer"),
154       };
155
156       RegistrationApplication::create(context.pool(), &form).await?;
157     }
158
159     // Email the admins
160     if local_site.application_email_admins {
161       send_new_applicant_email_to_admins(&data.username, context.pool(), context.settings())
162         .await?;
163     }
164
165     let mut login_response = LoginResponse {
166       jwt: None,
167       registration_created: false,
168       verify_email_sent: false,
169     };
170
171     // Log the user in directly if the site is not setup, or email verification and application aren't required
172     if !local_site.site_setup
173       || (!local_site.require_application && !local_site.require_email_verification)
174     {
175       login_response.jwt = Some(
176         Claims::jwt(
177           inserted_local_user.id.0,
178           &context.secret().jwt_secret,
179           &context.settings().hostname,
180         )?
181         .into(),
182       );
183     } else {
184       if local_site.require_email_verification {
185         let local_user_view = LocalUserView {
186           local_user: inserted_local_user,
187           person: inserted_person,
188           counts: PersonAggregates::default(),
189         };
190         // we check at the beginning of this method that email is set
191         let email = local_user_view
192           .local_user
193           .email
194           .clone()
195           .expect("email was provided");
196
197         send_verification_email(&local_user_view, &email, context.pool(), context.settings())
198           .await?;
199         login_response.verify_email_sent = true;
200       }
201
202       if local_site.require_application {
203         login_response.registration_created = true;
204       }
205     }
206
207     Ok(login_response)
208   }
209 }