]> Untitled Git - lemmy.git/blob - crates/api_crud/src/user/create.rs
Actor name length config dess (#1672)
[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, 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   settings::structs::Settings,
33   utils::{check_slurs, is_valid_actor_name},
34   ApiError,
35   ConnectionId,
36   LemmyError,
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   async fn perform(
45     &self,
46     context: &Data<LemmyContext>,
47     _websocket_id: Option<ConnectionId>,
48   ) -> Result<LoginResponse, LemmyError> {
49     let data: &Register = self;
50
51     // Make sure site has open registration
52     if let Ok(site) = blocking(context.pool(), move |conn| Site::read_simple(conn)).await? {
53       if !site.open_registration {
54         return Err(ApiError::err("registration_closed").into());
55       }
56     }
57
58     password_length_check(&data.password)?;
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 && Settings::get().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)?;
92
93     let actor_keypair = generate_actor_keypair()?;
94     if !is_valid_actor_name(&data.username) {
95       return Err(ApiError::err("invalid_username").into());
96     }
97     let actor_id = generate_apub_endpoint(EndpointType::Person, &data.username)?;
98
99     // We have to create both a person, and local_user
100
101     // Register the new person
102     let person_form = PersonForm {
103       name: data.username.to_owned(),
104       actor_id: Some(actor_id.clone()),
105       private_key: Some(Some(actor_keypair.private_key)),
106       public_key: Some(Some(actor_keypair.public_key)),
107       inbox_url: Some(generate_inbox_url(&actor_id)?),
108       shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
109       admin: Some(no_admins),
110       ..PersonForm::default()
111     };
112
113     // insert the person
114     let inserted_person = blocking(context.pool(), move |conn| {
115       Person::create(conn, &person_form)
116     })
117     .await?
118     .map_err(|_| ApiError::err("user_already_exists"))?;
119
120     // Create the local user
121     // TODO some of these could probably use the DB defaults
122     let local_user_form = LocalUserForm {
123       person_id: inserted_person.id,
124       email: Some(data.email.to_owned()),
125       password_encrypted: data.password.to_owned(),
126       show_nsfw: Some(data.show_nsfw),
127       show_bot_accounts: Some(true),
128       theme: Some("browser".into()),
129       default_sort_type: Some(SortType::Active as i16),
130       default_listing_type: Some(ListingType::Subscribed as i16),
131       lang: Some("browser".into()),
132       show_avatars: Some(true),
133       show_scores: Some(true),
134       show_read_posts: Some(true),
135       show_new_post_notifs: Some(false),
136       send_notifications_to_email: Some(false),
137     };
138
139     let inserted_local_user = match blocking(context.pool(), move |conn| {
140       LocalUser::register(conn, &local_user_form)
141     })
142     .await?
143     {
144       Ok(lu) => lu,
145       Err(e) => {
146         let err_type = if e.to_string()
147           == "duplicate key value violates unique constraint \"local_user_email_key\""
148         {
149           "email_already_exists"
150         } else {
151           "user_already_exists"
152         };
153
154         // If the local user creation errored, then delete that person
155         blocking(context.pool(), move |conn| {
156           Person::delete(conn, inserted_person.id)
157         })
158         .await??;
159
160         return Err(ApiError::err(err_type).into());
161       }
162     };
163
164     let main_community_keypair = generate_actor_keypair()?;
165
166     // Create the main community if it doesn't exist
167     let main_community = match blocking(context.pool(), move |conn| {
168       Community::read(conn, CommunityId(2))
169     })
170     .await?
171     {
172       Ok(c) => c,
173       Err(_e) => {
174         let default_community_name = "main";
175         let actor_id = generate_apub_endpoint(EndpointType::Community, default_community_name)?;
176         let community_form = CommunityForm {
177           name: default_community_name.to_string(),
178           title: "The Default Community".to_string(),
179           description: Some("The Default Community".to_string()),
180           actor_id: Some(actor_id.to_owned()),
181           private_key: Some(main_community_keypair.private_key),
182           public_key: Some(main_community_keypair.public_key),
183           followers_url: Some(generate_followers_url(&actor_id)?),
184           inbox_url: Some(generate_inbox_url(&actor_id)?),
185           shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
186           ..CommunityForm::default()
187         };
188         blocking(context.pool(), move |conn| {
189           Community::create(conn, &community_form)
190         })
191         .await??
192       }
193     };
194
195     // Sign them up for main community no matter what
196     let community_follower_form = CommunityFollowerForm {
197       community_id: main_community.id,
198       person_id: inserted_person.id,
199       pending: false,
200     };
201
202     let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
203     if blocking(context.pool(), follow).await?.is_err() {
204       return Err(ApiError::err("community_follower_already_exists").into());
205     };
206
207     // If its an admin, add them as a mod and follower to main
208     if no_admins {
209       let community_moderator_form = CommunityModeratorForm {
210         community_id: main_community.id,
211         person_id: inserted_person.id,
212       };
213
214       let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
215       if blocking(context.pool(), join).await?.is_err() {
216         return Err(ApiError::err("community_moderator_already_exists").into());
217       }
218     }
219
220     // Return the jwt
221     Ok(LoginResponse {
222       jwt: Claims::jwt(inserted_local_user.id.0)?,
223     })
224   }
225 }