]> Untitled Git - lemmy.git/blob - crates/api_crud/src/user/create.rs
Fix unapproved users being able to log in after registration mode set to closed....
[lemmy.git] / crates / api_crud / src / user / create.rs
1 use crate::PerformCrud;
2 use activitypub_federation::http_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_user::{LocalUser, LocalUserInsertForm},
23     person::{Person, PersonInsertForm},
24     registration_application::{RegistrationApplication, RegistrationApplicationInsertForm},
25   },
26   traits::Crud,
27   RegistrationMode,
28 };
29 use lemmy_db_views::structs::{LocalUserView, SiteView};
30 use lemmy_utils::{
31   claims::Claims,
32   error::LemmyError,
33   utils::{
34     slurs::{check_slurs, check_slurs_opt},
35     validation::is_valid_actor_name,
36   },
37 };
38
39 #[async_trait::async_trait(?Send)]
40 impl PerformCrud for Register {
41   type Response = LoginResponse;
42
43   #[tracing::instrument(skip(self, context))]
44   async fn perform(&self, context: &Data<LemmyContext>) -> Result<LoginResponse, LemmyError> {
45     let data: &Register = self;
46
47     let site_view = SiteView::read_local(context.pool()).await?;
48     let local_site = site_view.local_site;
49     let require_registration_application =
50       local_site.registration_mode == RegistrationMode::RequireApplication;
51
52     if local_site.registration_mode == RegistrationMode::Closed {
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 && require_registration_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     let slur_regex = local_site_to_slur_regex(&local_site);
75     check_slurs(&data.username, &slur_regex)?;
76     check_slurs_opt(&data.answer, &slur_regex)?;
77
78     let actor_keypair = generate_actor_keypair()?;
79     is_valid_actor_name(&data.username, local_site.actor_name_max_length as usize)?;
80     let actor_id = generate_local_apub_endpoint(
81       EndpointType::Person,
82       &data.username,
83       &context.settings().get_protocol_and_hostname(),
84     )?;
85
86     // We have to create both a person, and local_user
87
88     // Register the new person
89     let person_form = PersonInsertForm::builder()
90       .name(data.username.clone())
91       .actor_id(Some(actor_id.clone()))
92       .private_key(Some(actor_keypair.private_key))
93       .public_key(actor_keypair.public_key)
94       .inbox_url(Some(generate_inbox_url(&actor_id)?))
95       .shared_inbox_url(Some(generate_shared_inbox_url(&actor_id)?))
96       // If its the initial site setup, they are an admin
97       .admin(Some(!local_site.site_setup))
98       .instance_id(site_view.site.instance_id)
99       .build();
100
101     // insert the person
102     let inserted_person = Person::create(context.pool(), &person_form)
103       .await
104       .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?;
105
106     // Automatically set their application as accepted, if they created this with open registration.
107     // Also fixes a bug which allows users to log in when registrations are changed to closed.
108     let accepted_application = Some(!require_registration_application);
109
110     // Create the local user
111     let local_user_form = LocalUserInsertForm::builder()
112       .person_id(inserted_person.id)
113       .email(data.email.as_deref().map(str::to_lowercase))
114       .password_encrypted(data.password.to_string())
115       .show_nsfw(Some(data.show_nsfw))
116       .accepted_application(accepted_application)
117       .build();
118
119     let inserted_local_user = match LocalUser::create(context.pool(), &local_user_form).await {
120       Ok(lu) => lu,
121       Err(e) => {
122         let err_type = if e.to_string()
123           == "duplicate key value violates unique constraint \"local_user_email_key\""
124         {
125           "email_already_exists"
126         } else {
127           "user_already_exists"
128         };
129
130         // If the local user creation errored, then delete that person
131         Person::delete(context.pool(), inserted_person.id).await?;
132
133         return Err(LemmyError::from_error_message(e, err_type));
134       }
135     };
136
137     if local_site.site_setup && require_registration_application {
138       // Create the registration application
139       let form = RegistrationApplicationInsertForm {
140         local_user_id: inserted_local_user.id,
141         // We already made sure answer was not null above
142         answer: data.answer.clone().expect("must have an answer"),
143       };
144
145       RegistrationApplication::create(context.pool(), &form).await?;
146     }
147
148     // Email the admins
149     if local_site.application_email_admins {
150       send_new_applicant_email_to_admins(&data.username, context.pool(), context.settings())
151         .await?;
152     }
153
154     let mut login_response = LoginResponse {
155       jwt: None,
156       registration_created: false,
157       verify_email_sent: false,
158     };
159
160     // Log the user in directly if the site is not setup, or email verification and application aren't required
161     if !local_site.site_setup
162       || (!require_registration_application && !local_site.require_email_verification)
163     {
164       login_response.jwt = Some(
165         Claims::jwt(
166           inserted_local_user.id.0,
167           &context.secret().jwt_secret,
168           &context.settings().hostname,
169         )?
170         .into(),
171       );
172     } else {
173       if local_site.require_email_verification {
174         let local_user_view = LocalUserView {
175           local_user: inserted_local_user,
176           person: inserted_person,
177           counts: PersonAggregates::default(),
178         };
179         // we check at the beginning of this method that email is set
180         let email = local_user_view
181           .local_user
182           .email
183           .clone()
184           .expect("email was provided");
185
186         send_verification_email(&local_user_view, &email, context.pool(), context.settings())
187           .await?;
188         login_response.verify_email_sent = true;
189       }
190
191       if require_registration_application {
192         login_response.registration_created = true;
193       }
194     }
195
196     Ok(login_response)
197   }
198 }