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