]> Untitled Git - lemmy.git/blob - crates/api_crud/src/user/create.rs
Sanitize html (#3708)
[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     sanitize_html,
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, CheckCaptchaAnswer},
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, LemmyErrorExt, LemmyErrorType},
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(&mut 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(LemmyErrorType::RegistrationClosed)?;
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(LemmyErrorType::EmailRequired)?;
63     }
64
65     if local_site.site_setup && require_registration_application && data.answer.is_none() {
66       return Err(LemmyErrorType::RegistrationApplicationAnswerRequired)?;
67     }
68
69     // Make sure passwords match
70     if data.password != data.password_verify {
71       return Err(LemmyErrorType::PasswordsDoNotMatch)?;
72     }
73
74     if local_site.site_setup && local_site.captcha_enabled {
75       if let Some(captcha_uuid) = &data.captcha_uuid {
76         let uuid = uuid::Uuid::parse_str(captcha_uuid)?;
77         let check = CaptchaAnswer::check_captcha(
78           &mut context.pool(),
79           CheckCaptchaAnswer {
80             uuid,
81             answer: data.captcha_answer.clone().unwrap_or_default(),
82           },
83         )
84         .await?;
85         if !check {
86           return Err(LemmyErrorType::CaptchaIncorrect)?;
87         }
88       } else {
89         return Err(LemmyErrorType::CaptchaIncorrect)?;
90       }
91     }
92
93     let slur_regex = local_site_to_slur_regex(&local_site);
94     check_slurs(&data.username, &slur_regex)?;
95     check_slurs_opt(&data.answer, &slur_regex)?;
96     let username = sanitize_html(&data.username);
97
98     let actor_keypair = generate_actor_keypair()?;
99     is_valid_actor_name(&data.username, local_site.actor_name_max_length as usize)?;
100     let actor_id = generate_local_apub_endpoint(
101       EndpointType::Person,
102       &data.username,
103       &context.settings().get_protocol_and_hostname(),
104     )?;
105
106     if let Some(email) = &data.email {
107       if LocalUser::is_email_taken(&mut context.pool(), email).await? {
108         return Err(LemmyErrorType::EmailAlreadyExists)?;
109       }
110     }
111
112     // We have to create both a person, and local_user
113
114     // Register the new person
115     let person_form = PersonInsertForm::builder()
116       .name(username)
117       .actor_id(Some(actor_id.clone()))
118       .private_key(Some(actor_keypair.private_key))
119       .public_key(actor_keypair.public_key)
120       .inbox_url(Some(generate_inbox_url(&actor_id)?))
121       .shared_inbox_url(Some(generate_shared_inbox_url(&actor_id)?))
122       // If its the initial site setup, they are an admin
123       .admin(Some(!local_site.site_setup))
124       .instance_id(site_view.site.instance_id)
125       .build();
126
127     // insert the person
128     let inserted_person = Person::create(&mut context.pool(), &person_form)
129       .await
130       .with_lemmy_type(LemmyErrorType::UserAlreadyExists)?;
131
132     // Automatically set their application as accepted, if they created this with open registration.
133     // Also fixes a bug which allows users to log in when registrations are changed to closed.
134     let accepted_application = Some(!require_registration_application);
135
136     // Create the local user
137     let local_user_form = LocalUserInsertForm::builder()
138       .person_id(inserted_person.id)
139       .email(data.email.as_deref().map(str::to_lowercase))
140       .password_encrypted(data.password.to_string())
141       .show_nsfw(Some(data.show_nsfw))
142       .accepted_application(accepted_application)
143       .default_listing_type(Some(local_site.default_post_listing_type))
144       .build();
145
146     let inserted_local_user = LocalUser::create(&mut context.pool(), &local_user_form).await?;
147
148     if local_site.site_setup && require_registration_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(&mut 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, &mut 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       || (!require_registration_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(
198           &local_user_view,
199           &email,
200           &mut context.pool(),
201           context.settings(),
202         )
203         .await?;
204         login_response.verify_email_sent = true;
205       }
206
207       if require_registration_application {
208         login_response.registration_created = true;
209       }
210     }
211
212     Ok(login_response)
213   }
214 }