]> Untitled Git - lemmy.git/blob - crates/api_crud/src/user/create.rs
Check for slurs in account creation. (#2443)
[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, check_slurs_opt, 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     let slur_regex = &context.settings().slur_regex();
103     check_slurs(&data.username, slur_regex)?;
104     check_slurs_opt(&data.answer, slur_regex)?;
105
106     let actor_keypair = generate_actor_keypair()?;
107     if !is_valid_actor_name(&data.username, context.settings().actor_name_max_length) {
108       return Err(LemmyError::from_message("invalid_username"));
109     }
110     let actor_id = generate_local_apub_endpoint(
111       EndpointType::Person,
112       &data.username,
113       &context.settings().get_protocol_and_hostname(),
114     )?;
115
116     // We have to create both a person, and local_user
117
118     // Register the new person
119     let person_form = PersonForm {
120       name: data.username.to_owned(),
121       actor_id: Some(actor_id.clone()),
122       private_key: Some(Some(actor_keypair.private_key)),
123       public_key: Some(actor_keypair.public_key),
124       inbox_url: Some(generate_inbox_url(&actor_id)?),
125       shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
126       admin: Some(no_admins),
127       ..PersonForm::default()
128     };
129
130     // insert the person
131     let inserted_person = blocking(context.pool(), move |conn| {
132       Person::create(conn, &person_form)
133     })
134     .await?
135     .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?;
136
137     // Create the local user
138     let local_user_form = LocalUserForm {
139       person_id: Some(inserted_person.id),
140       email: Some(data.email.as_deref().map(|s| s.to_owned())),
141       password_encrypted: Some(data.password.to_string()),
142       show_nsfw: Some(data.show_nsfw),
143       email_verified: Some(false),
144       ..LocalUserForm::default()
145     };
146
147     let inserted_local_user = match blocking(context.pool(), move |conn| {
148       LocalUser::register(conn, &local_user_form)
149     })
150     .await?
151     {
152       Ok(lu) => lu,
153       Err(e) => {
154         let err_type = if e.to_string()
155           == "duplicate key value violates unique constraint \"local_user_email_key\""
156         {
157           "email_already_exists"
158         } else {
159           "user_already_exists"
160         };
161
162         // If the local user creation errored, then delete that person
163         blocking(context.pool(), move |conn| {
164           Person::delete(conn, inserted_person.id)
165         })
166         .await??;
167
168         return Err(LemmyError::from_error_message(e, err_type));
169       }
170     };
171
172     if require_application {
173       // Create the registration application
174       let form = RegistrationApplicationForm {
175         local_user_id: Some(inserted_local_user.id),
176         // We already made sure answer was not null above
177         answer: data.answer.to_owned(),
178         ..RegistrationApplicationForm::default()
179       };
180
181       blocking(context.pool(), move |conn| {
182         RegistrationApplication::create(conn, &form)
183       })
184       .await??;
185     }
186
187     let mut login_response = LoginResponse {
188       jwt: None,
189       registration_created: false,
190       verify_email_sent: false,
191     };
192
193     // Log the user in directly if email verification and application aren't required
194     if !require_application && !email_verification {
195       login_response.jwt = Some(
196         Claims::jwt(
197           inserted_local_user.id.0,
198           &context.secret().jwt_secret,
199           &context.settings().hostname,
200         )?
201         .into(),
202       );
203     } else {
204       if email_verification {
205         let local_user_view = LocalUserView {
206           local_user: inserted_local_user,
207           person: inserted_person,
208           counts: PersonAggregates::default(),
209         };
210         // we check at the beginning of this method that email is set
211         let email = local_user_view
212           .local_user
213           .email
214           .clone()
215           .expect("email was provided");
216         send_verification_email(&local_user_view, &email, context.pool(), context.settings())
217           .await?;
218         login_response.verify_email_sent = true;
219       }
220
221       if require_application {
222         login_response.registration_created = true;
223       }
224     }
225
226     Ok(login_response)
227   }
228 }