]> Untitled Git - lemmy.git/blob - crates/api_crud/src/user/create.rs
caba9bd8ab44c4eeaa81429e5e0315d249764c0a
[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     captcha_answer::{CaptchaAnswer, CheckCaptchaAnswer},
23     local_user::{LocalUser, LocalUserInsertForm},
24     person::{Person, PersonInsertForm},
25     registration_application::{RegistrationApplication, RegistrationApplicationInsertForm},
26   },
27   traits::Crud,
28   RegistrationMode,
29 };
30 use lemmy_db_views::structs::{LocalUserView, SiteView};
31 use lemmy_utils::{
32   claims::Claims,
33   error::{LemmyError, LemmyErrorExt, LemmyErrorType},
34   utils::{
35     slurs::{check_slurs, check_slurs_opt},
36     validation::is_valid_actor_name,
37   },
38 };
39
40 #[async_trait::async_trait(?Send)]
41 impl PerformCrud for Register {
42   type Response = LoginResponse;
43
44   #[tracing::instrument(skip(self, context))]
45   async fn perform(&self, context: &Data<LemmyContext>) -> Result<LoginResponse, LemmyError> {
46     let data: &Register = self;
47
48     let site_view = SiteView::read_local(&mut context.pool()).await?;
49     let local_site = site_view.local_site;
50     let require_registration_application =
51       local_site.registration_mode == RegistrationMode::RequireApplication;
52
53     if local_site.registration_mode == RegistrationMode::Closed {
54       return Err(LemmyErrorType::RegistrationClosed)?;
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(LemmyErrorType::EmailRequired)?;
62     }
63
64     if local_site.site_setup && require_registration_application && data.answer.is_none() {
65       return Err(LemmyErrorType::RegistrationApplicationAnswerRequired)?;
66     }
67
68     // Make sure passwords match
69     if data.password != data.password_verify {
70       return Err(LemmyErrorType::PasswordsDoNotMatch)?;
71     }
72
73     if local_site.site_setup && local_site.captcha_enabled {
74       if let Some(captcha_uuid) = &data.captcha_uuid {
75         let uuid = uuid::Uuid::parse_str(captcha_uuid)?;
76         let check = CaptchaAnswer::check_captcha(
77           &mut context.pool(),
78           CheckCaptchaAnswer {
79             uuid,
80             answer: data.captcha_answer.clone().unwrap_or_default(),
81           },
82         )
83         .await?;
84         if !check {
85           return Err(LemmyErrorType::CaptchaIncorrect)?;
86         }
87       } else {
88         return Err(LemmyErrorType::CaptchaIncorrect)?;
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(&mut context.pool(), email).await? {
106         return Err(LemmyErrorType::EmailAlreadyExists)?;
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(&mut context.pool(), &person_form)
127       .await
128       .with_lemmy_type(LemmyErrorType::UserAlreadyExists)?;
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       .default_listing_type(Some(local_site.default_post_listing_type))
142       .build();
143
144     let inserted_local_user = LocalUser::create(&mut context.pool(), &local_user_form).await?;
145
146     if local_site.site_setup && require_registration_application {
147       // Create the registration application
148       let form = RegistrationApplicationInsertForm {
149         local_user_id: inserted_local_user.id,
150         // We already made sure answer was not null above
151         answer: data.answer.clone().expect("must have an answer"),
152       };
153
154       RegistrationApplication::create(&mut context.pool(), &form).await?;
155     }
156
157     // Email the admins
158     if local_site.application_email_admins {
159       send_new_applicant_email_to_admins(&data.username, &mut context.pool(), context.settings())
160         .await?;
161     }
162
163     let mut login_response = LoginResponse {
164       jwt: None,
165       registration_created: false,
166       verify_email_sent: false,
167     };
168
169     // Log the user in directly if the site is not setup, or email verification and application aren't required
170     if !local_site.site_setup
171       || (!require_registration_application && !local_site.require_email_verification)
172     {
173       login_response.jwt = Some(
174         Claims::jwt(
175           inserted_local_user.id.0,
176           &context.secret().jwt_secret,
177           &context.settings().hostname,
178         )?
179         .into(),
180       );
181     } else {
182       if local_site.require_email_verification {
183         let local_user_view = LocalUserView {
184           local_user: inserted_local_user,
185           person: inserted_person,
186           counts: PersonAggregates::default(),
187         };
188         // we check at the beginning of this method that email is set
189         let email = local_user_view
190           .local_user
191           .email
192           .clone()
193           .expect("email was provided");
194
195         send_verification_email(
196           &local_user_view,
197           &email,
198           &mut context.pool(),
199           context.settings(),
200         )
201         .await?;
202         login_response.verify_email_sent = true;
203       }
204
205       if require_registration_application {
206         login_response.registration_created = true;
207       }
208     }
209
210     Ok(login_response)
211   }
212 }