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