restapi 1.1.14

A secure-by-default rest api using hyper, tokio, bb8, kafka-threadpool, postgres, and prometheus for monitoring
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Module for creating a user
//!
//! ## Create User
//!
//! Create a single ``users`` record for the new user
//!
//! - URL path: ``/user``
//! - Method: ``POST``
//! - Handler: [`create_user`](crate::requests::user::create_user::create_user)
//! - Request: [`ApiReqUserCreate`](crate::requests::user::create_user::ApiReqUserCreate)
//! - Response: [`ApiResUserCreate`](crate::requests::user::create_user::ApiResUserCreate)
//!

use std::convert::Infallible;

use postgres_native_tls::MakeTlsConnector;

use bb8::Pool;
use bb8_postgres::PostgresConnectionManager;

use hyper::Body;
use hyper::Response;

use serde::Deserialize;
use serde::Serialize;

use argon2::hash_encoded as argon_hash_encoded;
use argon2::Config as argon_config;

use kafka_threadpool::kafka_publisher::KafkaPublisher;

use crate::core::core_config::CoreConfig;
use crate::kafka::publish_msg::publish_msg;
use crate::requests::auth::create_user_token::create_user_token;
use crate::requests::auth::login_user::ApiResUserLogin;
use crate::requests::user::is_verification_enabled::is_verification_enabled;
use crate::requests::user::upsert_user_verification::upsert_user_verification;
use crate::utils::get_server_address::get_server_address;

/// ApiReqUserCreate
///
/// # Request Type For create_user
///
/// Create a new user in the db
///
/// This type is the deserialized input for:
/// [`create_user`](crate::requests::user::create_user::create_user]
///
/// # Usage
///
/// This type is constructed from the deserialized
/// `bytes` (`&[u8]`) argument
/// on the
/// [`create_user`](crate::requests::user::create_user::create_user)
/// function.
///
/// # Arguments
///
/// * `email` - `String` - user email
/// * `password` - `String` - new user password
///
#[derive(Serialize, Deserialize, Clone)]
pub struct ApiReqUserCreate {
    pub email: String,
    pub password: String,
}

/// ApiResUserCreate
///
/// # Response type for create_user
///
/// Return users's db record with encrypted jwt
///
/// # Usage
///
/// This type is the serialized output for the function:
/// [`create_user`](crate::requests::user::create_user::create_user]
/// and contained within the
/// hyper [`Body`](hyper::Body)
/// of the
/// hyper [`Response`](hyper::Response)
/// sent back to the client.
///
/// # Arguments
///
/// * `user_id` - `i32` - user id
/// * `email` - `String` - user email
/// * `state` - `i32` - user state where
///   (`0` - active, `1` - inactive)
/// * `role` - `String` - user role
/// * `token` - `String` - user jwt
/// * `msg` - `String` - help message
///
#[derive(Serialize, Deserialize, Default, Clone)]
pub struct ApiResUserCreate {
    pub user_id: i32,
    pub email: String,
    pub state: i32,
    pub role: String,
    pub token: String,
    pub msg: String,
}

/// create_user
///
/// Create a new user from the deserialized
/// [`ApiReqUserCreate`](crate::requests::user::create_user::ApiReqUserCreate)
/// json values from the `bytes` argument.
///
/// Also create a new user jwt and
/// email verification record (if enabled).
///
/// # Arguments
///
/// * `tracking_label` - `&str` - caller logging label
/// * `config` - [`CoreConfig`](crate::core::core_config::CoreConfig)
/// * `db_pool` - [`Pool`](bb8::Pool) - postgres client
///   db threadpool with required tls encryption
/// * `kafka_pool` -
///   [`KafkaPublisher`](kafka_threadpool::kafka_publisher::KafkaPublisher)
///   for asynchronously publishing messages to the connected kafka cluster
/// * `bytes` - `&[u8]` - received bytes from the hyper
///   [`Request`](hyper::Request)'s [`Body`](hyper::Body)
///
/// # Returns
///
/// ## create_user on Success Returns
///
/// The new user record from the db and a jwt for auto-auth.
/// (token created by
/// [`create_user_token`](crate::requests::auth::create_user_token::create_user_token)
/// )
///
/// hyper [`Response`](hyper::Response)
/// containing a json-serialized
/// [`ApiResUserCreate`](crate::requests::user::create_user::ApiResUserCreate)
/// dictionary within the
/// [`Body`](hyper::Body) and a
/// `201` HTTP status code
///
/// Ok([`Response`](hyper::Response))
///
/// # Errors
///
/// ## create_user on Failure Returns
///
/// All errors return as a
/// hyper [`Response`](hyper::Response)
/// containing a json-serialized
/// [`ApiResUserCreate`](crate::requests::user::create_user::ApiResUserCreate)
/// dictionary with a
/// `non-201` HTTP status code
///
/// Err([`Response`](hyper::Response))
///
pub async fn create_user(
    tracking_label: &str,
    config: &CoreConfig,
    db_pool: &Pool<PostgresConnectionManager<MakeTlsConnector>>,
    kafka_pool: &KafkaPublisher,
    bytes: &[u8],
) -> std::result::Result<Response<Body>, Infallible> {
    let user_object: ApiReqUserCreate = serde_json::from_slice(bytes).unwrap();

    if user_object.password.len() < 4 {
        let response = Response::builder()
            .status(400)
            .body(Body::from(
                serde_json::to_string(&ApiResUserCreate {
                    user_id: -1,
                    email: "".to_string(),
                    state: -1,
                    role: "".to_string(),
                    token: "".to_string(),
                    msg: ("User password must be more than 4 characters")
                        .to_string(),
                })
                .unwrap(),
            ))
            .unwrap();
        return Ok(response);
    }

    let mut user_role = "user";
    if user_object.email == "admin@email.com" {
        user_role = "admin";
    }

    let user_verification_enabled = is_verification_enabled();
    let user_start_state_value = 0;
    let user_verified_value = match user_verification_enabled {
        true => 0,
        false => 1,
    };

    // salt the user's password
    let argon_config = argon_config::default();
    let hash = argon_hash_encoded(
        user_object.password.as_bytes(),
        &config.server_password_salt,
        &argon_config,
    )
    .unwrap();

    let insert_query = format!(
        "INSERT INTO \
            users (\
                email, \
                password, \
                state, \
                verified, \
                role) \
        VALUES (\
            '{}', \
            '{hash}', \
            {user_start_state_value}, \
            {user_verified_value}, \
            '{user_role}') \
        RETURNING \
            users.id, \
            users.email, \
            users.password, \
            users.state, \
            users.verified, \
            users.role;",
        user_object.email
    );
    let conn = db_pool.get().await.unwrap();
    let stmt = conn.prepare(&insert_query).await.unwrap();
    let query_result = match conn.query(&stmt, &[]).await {
        Ok(query_result) => query_result,
        Err(e) => {
            let err_msg = format!("{e}");
            if err_msg.contains("duplicate key value violates") {
                let response = Response::builder()
                    .status(400)
                    .body(Body::from(
                        serde_json::to_string(&ApiResUserCreate {
                            user_id: -1,
                            email: "".to_string(),
                            state: -1,
                            role: "".to_string(),
                            token: "".to_string(),
                            msg: format!(
                                "User email {} already registered",
                                user_object.email
                            ),
                        })
                        .unwrap(),
                    ))
                    .unwrap();
                return Ok(response);
            } else {
                let response = Response::builder()
                    .status(500)
                    .body(Body::from(
                        serde_json::to_string(
                            &ApiResUserCreate {
                                user_id: -1,
                                email: "".to_string(),
                                state: -1,
                                role: "".to_string(),
                                token: "".to_string(),
                                msg: format!(
                                    "User creation failed for email={} with err='{err_msg}'",
                                        user_object.email)
                        }).unwrap()))
                    .unwrap();
                return Ok(response);
            }
        }
    };

    let mut row_list: Vec<(i32, String, String, i32, i32, String)> =
        Vec::with_capacity(1);
    for row in query_result.iter() {
        let id: i32 = row.try_get("id").unwrap();
        let email: String = row.try_get("email").unwrap();
        let password: String = row.try_get("password").unwrap();
        if password != hash {
            error!("BAD PASSWORD FOUND DURING USER CREATION:\npassword=\n{password}\n!=\nsalt=\n{hash}");
            let response = Response::builder()
                .status(400)
                .body(Body::from(
                    serde_json::to_string(&ApiResUserLogin {
                        user_id: -1,
                        email: "".to_string(),
                        state: -1,
                        verified: -1,
                        role: "".to_string(),
                        token: "".to_string(),
                        msg: ("User login failed - invalid password")
                            .to_string(),
                    })
                    .unwrap(),
                ))
                .unwrap();
            return Ok(response);
        }
        let user_state: i32 = row.try_get("state").unwrap();
        let user_verified_db: i32 = row.try_get("verified").unwrap();
        let role: String = row.try_get("role").unwrap();
        row_list.push((id, email, password, user_state, user_verified_db, role))
    }
    if row_list.is_empty() {
        let response = Response::builder()
            .status(400)
            .body(Body::from(
                serde_json::to_string(
                    &ApiResUserLogin {
                        user_id: -1,
                        email: "".to_string(),
                        state: -1,
                        verified: -1,
                        role: "".to_string(),
                        token: "".to_string(),
                        msg: format!(
                            "User creation failed - user does not exist with email={}",
                                user_object.email)
                    }
                ).unwrap()))
            .unwrap();
        Ok(response)
    } else {
        let user_id = row_list[0].0;
        let user_email = row_list[0].1.clone();
        let user_token = match create_user_token(
            tracking_label,
            config,
            &conn,
            &user_email,
            user_id,
        )
        .await
        {
            Ok(user_token) => user_token,
            Err(_) => {
                let response = Response::builder()
                    .status(500)
                    .body(Body::from(
                        serde_json::to_string(
                            &ApiResUserLogin {
                                user_id: -1,
                                email: "".to_string(),
                                state: -1,
                                verified: -1,
                                role: "".to_string(),
                                token: "".to_string(),
                                msg: format!("User token creation failed - {user_id} {user_email}"),
                            }
                        ).unwrap()))
                    .unwrap();
                return Ok(response);
            }
        };
        if user_verification_enabled {
            match upsert_user_verification(
                tracking_label,
                user_id,
                &user_email,
                true, // is new user flag
                0,    // not verified
                &conn,
            )
            .await
            {
                Ok(verification_token) => {
                    info!(
                        "{tracking_label} - verify token created user={user_id} \
                        {user_email} - verify url:\
                        curl -ks \
                        \"https://{}/user/verify?u={user_id}&t={verification_token}\" \
                        | jq",
                            get_server_address("api"));
                }
                Err(e) => {
                    error!(
                        "{tracking_label} - \
                        failed to generate verify token for user {user_id} \
                        {user_email} with err='{e}'"
                    );
                }
            };
        }

        // if enabled, publish to kafka
        if config.kafka_publish_events {
            publish_msg(
                kafka_pool,
                // topic
                "user.events",
                // partition key
                &format!("user-{}", user_id),
                // optional headers stored in: Option<HashMap<String, String>>
                None,
                // payload in the message
                &format!("USER_CREATE user={user_id} email={user_email}"),
            )
            .await;
        }

        let response = Response::builder()
            .status(201)
            .body(Body::from(
                serde_json::to_string(&ApiResUserLogin {
                    user_id,
                    email: user_email,
                    state: row_list[0].3,
                    verified: row_list[0].4,
                    role: row_list[0].5.clone(),
                    token: user_token,
                    msg: "success".to_string(),
                })
                .unwrap(),
            ))
            .unwrap();
        Ok(response)
    }
}