]> Untitled Git - lemmy.git/blob - crates/api_crud/src/user/create.rs
Adding honeypot to user and post creation. Fixes #1802 (#1803)
[lemmy.git] / crates / api_crud / src / user / create.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{blocking, honeypot_check, password_length_check, person::*};
4 use lemmy_apub::{
5   generate_apub_endpoint,
6   generate_followers_url,
7   generate_inbox_url,
8   generate_shared_inbox_url,
9   EndpointType,
10 };
11 use lemmy_db_queries::{
12   source::{local_user::LocalUser_, site::Site_},
13   Crud,
14   Followable,
15   Joinable,
16   ListingType,
17   SortType,
18 };
19 use lemmy_db_schema::{
20   source::{
21     community::*,
22     local_user::{LocalUser, LocalUserForm},
23     person::*,
24     site::*,
25   },
26   CommunityId,
27 };
28 use lemmy_db_views_actor::person_view::PersonViewSafe;
29 use lemmy_utils::{
30   apub::generate_actor_keypair,
31   claims::Claims,
32   utils::{check_slurs, is_valid_actor_name},
33   ApiError,
34   ConnectionId,
35   LemmyError,
36 };
37 use lemmy_websocket::{messages::CheckCaptcha, LemmyContext};
38
39 #[async_trait::async_trait(?Send)]
40 impl PerformCrud for Register {
41   type Response = LoginResponse;
42
43   async fn perform(
44     &self,
45     context: &Data<LemmyContext>,
46     _websocket_id: Option<ConnectionId>,
47   ) -> Result<LoginResponse, LemmyError> {
48     let data: &Register = self;
49
50     // Make sure site has open registration
51     if let Ok(site) = blocking(context.pool(), move |conn| Site::read_simple(conn)).await? {
52       if !site.open_registration {
53         return Err(ApiError::err("registration_closed").into());
54       }
55     }
56
57     password_length_check(&data.password)?;
58     honeypot_check(&data.honeypot)?;
59
60     // Make sure passwords match
61     if data.password != data.password_verify {
62       return Err(ApiError::err("passwords_dont_match").into());
63     }
64
65     // Check if there are admins. False if admins exist
66     let no_admins = blocking(context.pool(), move |conn| {
67       PersonViewSafe::admins(conn).map(|a| a.is_empty())
68     })
69     .await??;
70
71     // If its not the admin, check the captcha
72     if !no_admins && context.settings().captcha.enabled {
73       let check = context
74         .chat_server()
75         .send(CheckCaptcha {
76           uuid: data
77             .captcha_uuid
78             .to_owned()
79             .unwrap_or_else(|| "".to_string()),
80           answer: data
81             .captcha_answer
82             .to_owned()
83             .unwrap_or_else(|| "".to_string()),
84         })
85         .await?;
86       if !check {
87         return Err(ApiError::err("captcha_incorrect").into());
88       }
89     }
90
91     check_slurs(&data.username, &context.settings().slur_regex())?;
92
93     let actor_keypair = generate_actor_keypair()?;
94     if !is_valid_actor_name(&data.username, context.settings().actor_name_max_length) {
95       return Err(ApiError::err("invalid_username").into());
96     }
97     let actor_id = generate_apub_endpoint(
98       EndpointType::Person,
99       &data.username,
100       &context.settings().get_protocol_and_hostname(),
101     )?;
102
103     // We have to create both a person, and local_user
104
105     // Register the new person
106     let person_form = PersonForm {
107       name: data.username.to_owned(),
108       actor_id: Some(actor_id.clone()),
109       private_key: Some(Some(actor_keypair.private_key)),
110       public_key: Some(Some(actor_keypair.public_key)),
111       inbox_url: Some(generate_inbox_url(&actor_id)?),
112       shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
113       admin: Some(no_admins),
114       ..PersonForm::default()
115     };
116
117     // insert the person
118     let inserted_person = blocking(context.pool(), move |conn| {
119       Person::create(conn, &person_form)
120     })
121     .await?
122     .map_err(|_| ApiError::err("user_already_exists"))?;
123
124     // Create the local user
125     // TODO some of these could probably use the DB defaults
126     let local_user_form = LocalUserForm {
127       person_id: inserted_person.id,
128       email: Some(data.email.to_owned()),
129       password_encrypted: data.password.to_owned(),
130       show_nsfw: Some(data.show_nsfw),
131       show_bot_accounts: Some(true),
132       theme: Some("browser".into()),
133       default_sort_type: Some(SortType::Active as i16),
134       default_listing_type: Some(ListingType::Subscribed as i16),
135       lang: Some("browser".into()),
136       show_avatars: Some(true),
137       show_scores: Some(true),
138       show_read_posts: Some(true),
139       show_new_post_notifs: Some(false),
140       send_notifications_to_email: Some(false),
141     };
142
143     let inserted_local_user = match blocking(context.pool(), move |conn| {
144       LocalUser::register(conn, &local_user_form)
145     })
146     .await?
147     {
148       Ok(lu) => lu,
149       Err(e) => {
150         let err_type = if e.to_string()
151           == "duplicate key value violates unique constraint \"local_user_email_key\""
152         {
153           "email_already_exists"
154         } else {
155           "user_already_exists"
156         };
157
158         // If the local user creation errored, then delete that person
159         blocking(context.pool(), move |conn| {
160           Person::delete(conn, inserted_person.id)
161         })
162         .await??;
163
164         return Err(ApiError::err(err_type).into());
165       }
166     };
167
168     let main_community_keypair = generate_actor_keypair()?;
169
170     // Create the main community if it doesn't exist
171     let protocol_and_hostname = context.settings().get_protocol_and_hostname();
172     let main_community = match blocking(context.pool(), move |conn| {
173       Community::read(conn, CommunityId(2))
174     })
175     .await?
176     {
177       Ok(c) => c,
178       Err(_e) => {
179         let default_community_name = "main";
180         let actor_id = generate_apub_endpoint(
181           EndpointType::Community,
182           default_community_name,
183           &protocol_and_hostname,
184         )?;
185         let community_form = CommunityForm {
186           name: default_community_name.to_string(),
187           title: "The Default Community".to_string(),
188           description: Some("The Default Community".to_string()),
189           actor_id: Some(actor_id.to_owned()),
190           private_key: Some(main_community_keypair.private_key),
191           public_key: Some(main_community_keypair.public_key),
192           followers_url: Some(generate_followers_url(&actor_id)?),
193           inbox_url: Some(generate_inbox_url(&actor_id)?),
194           shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
195           ..CommunityForm::default()
196         };
197         blocking(context.pool(), move |conn| {
198           Community::create(conn, &community_form)
199         })
200         .await??
201       }
202     };
203
204     // Sign them up for main community no matter what
205     let community_follower_form = CommunityFollowerForm {
206       community_id: main_community.id,
207       person_id: inserted_person.id,
208       pending: false,
209     };
210
211     let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
212     if blocking(context.pool(), follow).await?.is_err() {
213       return Err(ApiError::err("community_follower_already_exists").into());
214     };
215
216     // If its an admin, add them as a mod and follower to main
217     if no_admins {
218       let community_moderator_form = CommunityModeratorForm {
219         community_id: main_community.id,
220         person_id: inserted_person.id,
221       };
222
223       let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
224       if blocking(context.pool(), join).await?.is_err() {
225         return Err(ApiError::err("community_moderator_already_exists").into());
226       }
227     }
228
229     // Return the jwt
230     Ok(LoginResponse {
231       jwt: Claims::jwt(
232         inserted_local_user.id.0,
233         &context.secret().jwt_secret,
234         &context.settings().hostname,
235       )?,
236     })
237   }
238 }