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