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