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