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
//! Module for creating a user's one-time-use password
//!
//! ## Create One-Time-Use Password Reset Token (OTP)
//!
//! Create a one-time-use password reset token that allows a user to change their ``users.password`` value by presenting the token
//!
//! - URL path: ``/user/password/reset``
//! - Method: ``POST``
//! - Handler: [`create_otp`](crate::requests::user::create_otp::create_otp)
//! - Request: [`ApiReqUserCreateOtp`](crate::requests::user::create_otp::ApiReqUserCreateOtp)
//! - Response: [`ApiResUserCreateOtp`](crate::requests::user::create_otp::ApiResUserCreateOtp)
//!

use std::convert::Infallible;

use postgres_native_tls::MakeTlsConnector;

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

use hyper::header::HeaderValue;
use hyper::Body;
use hyper::HeaderMap;
use hyper::Response;

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

use kafka_threadpool::kafka_publisher::KafkaPublisher;

use crate::core::core_config::CoreConfig;
use crate::kafka::publish_msg::publish_msg;
use crate::requests::auth::validate_user_token::validate_user_token;
use crate::requests::models::user::get_user_by_id;
use crate::utils::get_uuid::get_uuid;

/// ApiReqUserCreateOtp
///
/// # Request Type For create_otp
///
/// Creating a one-time-use password token for helping a user reset
/// their password (note: users should have a verified email to avoid
/// email spam).
///
/// This type is the deserialized input for:
/// [`create_otp`](crate::requests::user::create_otp::create_otp]
///
/// # Usage
///
/// This type is constructed from the deserialized
/// `bytes` (`&[u8]`) argument
/// on the
/// `create_otp`
/// function.
///
/// # Arguments
///
/// * `user_id` - `i32` - user id
/// * `email` - `String` - user email
///
#[derive(Serialize, Deserialize, Clone)]
pub struct ApiReqUserCreateOtp {
    // users.id
    pub user_id: i32,
    // users.email
    pub email: String,
}

/// ApiResUserCreateOtp
///
/// # Response type for create_otp
///
/// Notify the client that, the user's one-time-use password reset token
/// was consumed, and the user will need to call:
/// [`login_user`](crate::requests::auth::login_user::login_user)
/// to log in with the new password.
///
/// # Usage
///
/// This type is the serialized output for the function:
/// [`create_otp`](crate::requests::user::create_otp::create_otp]
/// 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
/// * `token` - `String` - user's new one-time-use token to reset
///   their password
/// * `exp_date` - `String` - UTC-formatted date time string when
///   the `token` expires
/// * `msg` - `String` - help message
///
#[derive(Serialize, Deserialize, Clone)]
pub struct ApiResUserCreateOtp {
    // users.id
    pub user_id: i32,
    // users_otp.token
    pub token: String,
    pub exp_date: String,
    pub msg: String,
}

/// create_otp
///
/// Creates a one-time-use token to reset a user's account password.
///
/// # 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
/// * `headers` - [`HeaderMap`](hyper::HeaderMap) -
///   hashmap containing headers in key-value pairs
///   [`Request`](hyper::Request)'s [`Body`](hyper::Body)
/// * `bytes` - `&[u8]` - received bytes from the hyper
///   [`Request`](hyper::Request)'s [`Body`](hyper::Body)
///
/// # Returns
///
/// ## Success
///
/// hyper [`Response`](hyper::Response)
/// containing a json-serialized
/// [`ApiResUserCreateOtp`](crate::requests::user::create_otp::ApiResUserCreateOtp)
/// dictionary within the
/// [`Body`](hyper::Body) and a
/// `201` HTTP status code
///
/// Ok([`Response`](hyper::Response))
///
/// # Errors
///
/// All errors return as a
/// hyper [`Response`](hyper::Response)
/// containing a json-serialized
/// [`ApiResUserCreateOtp`](crate::requests::user::create_otp::ApiResUserCreateOtp)
/// dictionary with a
/// `non-201` HTTP status code
///
/// Err([`Response`](hyper::Response))
///
pub async fn create_otp(
    tracking_label: &str,
    config: &CoreConfig,
    db_pool: &Pool<PostgresConnectionManager<MakeTlsConnector>>,
    kafka_pool: &KafkaPublisher,
    headers: &HeaderMap<HeaderValue>,
    bytes: &[u8],
) -> std::result::Result<Response<Body>, Infallible> {
    let req_object: ApiReqUserCreateOtp = match serde_json::from_slice(bytes) {
        Ok(uo) => uo,
        Err(_) => {
            let response = Response::builder()
                .status(400)
                .body(Body::from(
                    serde_json::to_string(&ApiResUserCreateOtp {
                        user_id: -1,
                        token: "".to_string(),
                        exp_date: "".to_string(),
                        msg: ("User create one-time-password failed - \
                            please ensure \
                            user_id and email \
                            were set correctly in the request")
                            .to_string(),
                    })
                    .unwrap(),
                ))
                .unwrap();
            return Ok(response);
        }
    };

    // is this a waste of time because nothing changed
    if req_object.user_id <= 0 {
        let response = Response::builder()
            .status(400)
            .body(Body::from(
                serde_json::to_string(&ApiResUserCreateOtp {
                    user_id: req_object.user_id,
                    token: "".to_string(),
                    exp_date: "".to_string(),
                    msg: ("User create one-time-password failed \
                        please ensure \
                        user_id is a non-negative number")
                        .to_string(),
                })
                .unwrap(),
            ))
            .unwrap();
        return Ok(response);
    } else if req_object.email.is_empty() {
        let response = Response::builder()
            .status(400)
            .body(Body::from(
                serde_json::to_string(&ApiResUserCreateOtp {
                    user_id: req_object.user_id,
                    token: "".to_string(),
                    exp_date: "".to_string(),
                    msg: ("User create one-time-password failed \
                        please ensure \
                        email is set to the user's email address")
                        .to_string(),
                })
                .unwrap(),
            ))
            .unwrap();
        return Ok(response);
    }

    let conn = db_pool.get().await.unwrap();

    let user_clone = req_object.clone();
    let user_id = user_clone.user_id;
    let user_email = user_clone.email;
    let _token = match validate_user_token(
        tracking_label,
        config,
        &conn,
        headers,
        user_id,
    )
    .await
    {
        Ok(_token) => _token,
        Err(_) => {
            let response = Response::builder()
                .status(400)
                .body(Body::from(
                    serde_json::to_string(&ApiResUserCreateOtp {
                        user_id: req_object.user_id,
                        token: "".to_string(),
                        exp_date: "".to_string(),
                        msg: ("User create one-time-password failed \
                            due to invalid token")
                            .to_string(),
                    })
                    .unwrap(),
                ))
                .unwrap();
            return Ok(response);
        }
    };

    // get the user and detect if the email is different
    let user_model = match get_user_by_id(tracking_label, user_id, &conn).await
    {
        Ok(user_model) => user_model,
        Err(err_msg) => {
            error!(
                "{tracking_label} - \
                failed to create one-time-password user {user_id} \
                with err='{err_msg}'"
            );
            let response = Response::builder()
                .status(400)
                .body(Body::from(
                    serde_json::to_string(&ApiResUserCreateOtp {
                        user_id: req_object.user_id,
                        token: "".to_string(),
                        exp_date: "".to_string(),
                        msg: format!(
                            "User create one-time-password failed - \
                            unable to find user with id: {user_id}"
                        ),
                    })
                    .unwrap(),
                ))
                .unwrap();
            return Ok(response);
        }
    };

    if user_model.email != req_object.email {
        let response = Response::builder()
            .status(400)
            .body(Body::from(
                serde_json::to_string(&ApiResUserCreateOtp {
                    user_id: req_object.user_id,
                    token: "".to_string(),
                    exp_date: "".to_string(),
                    msg: format!(
                        "User create one-time-password failed - \
                        user_email does not match {}",
                        req_object.email
                    ),
                })
                .unwrap(),
            ))
            .unwrap();
        return Ok(response);
    }

    let user_otp_expiration_in_seconds_str =
        std::env::var("USER_OTP_EXP_IN_SECONDS")
            .unwrap_or_else(|_| "2592000".to_string());
    let user_otp_expiration_in_seconds: i64 =
        user_otp_expiration_in_seconds_str.parse::<i64>().unwrap();
    let now = chrono::Utc::now();
    // https://docs.rs/chrono/0.4.19/chrono/struct.Duration.html#method.seconds
    let otp_expiration_timestamp =
        now + chrono::Duration::seconds(user_otp_expiration_in_seconds);

    let otp_token = format!("{}{}", get_uuid(), get_uuid());

    let cur_query = format!(
        "INSERT INTO \
            users_otp (\
                user_id, \
                token, \
                email, \
                state, \
                exp_date) \
        VALUES (\
            {user_id}, \
            '{otp_token}', \
            '{user_email}', \
            0,
            '{otp_expiration_timestamp}') \
        RETURNING \
            users_otp.id, \
            users_otp.user_id, \
            users_otp.token, \
            users_otp.email, \
            users_otp.state, \
            users_otp.exp_date;"
    );

    let stmt = conn.prepare(&cur_query).await.unwrap();
    let query_result = match conn.query(&stmt, &[]).await {
        Ok(query_result) => query_result,
        Err(e) => {
            let response = Response::builder()
                .status(400)
                .body(Body::from(
                    serde_json::to_string(&ApiResUserCreateOtp {
                        user_id: req_object.user_id,
                        token: "".to_string(),
                        exp_date: "".to_string(),
                        msg: format!(
                            "User create one-time-password failed \
                            for user_id={user_id} {user_email} \
                            with err='{e}'"
                        ),
                    })
                    .unwrap(),
                ))
                .unwrap();
            return Ok(response);
        }
    };

    // must match up with RETURNING
    if let Some(row) = query_result.first() {
        let user_otp_id: i32 = row.try_get("id").unwrap();
        let user_otp_token: String = row.try_get("token").unwrap();
        let user_otp_exp_date_str: String = match row.try_get("exp_date") {
            Ok(v) => {
                let user_otp_exp_date: chrono::DateTime<chrono::Utc> = v;
                format!("{}", user_otp_exp_date.format("%Y-%m-%dT%H:%M:%SZ"))
            }
            Err(_) => "".to_string(),
        };

        // 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_OTP user={user_id}"),
            )
            .await;
        }

        let response = Response::builder()
            .status(201)
            .body(Body::from(
                serde_json::to_string(&ApiResUserCreateOtp {
                    user_id: user_otp_id,
                    token: user_otp_token,
                    exp_date: user_otp_exp_date_str,
                    msg: "success".to_string(),
                })
                .unwrap(),
            ))
            .unwrap();
        return Ok(response);
    }
    let response = Response::builder()
        .status(400)
        .body(Body::from(
            serde_json::to_string(&ApiResUserCreateOtp {
                user_id: req_object.user_id,
                token: "".to_string(),
                exp_date: "".to_string(),
                msg: ("User create one-time-password failed - \
                    no records found in db")
                    .to_string(),
            })
            .unwrap(),
        ))
        .unwrap();
    Ok(response)
}