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