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