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