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