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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
use tera::Context;
use std::{
    path::PathBuf, 
    collections::HashMap, 
    sync::RwLock,
};
use hyper::{
    client::HttpConnector,
    header,
    header::COOKIE,
    service::{make_service_fn, service_fn},
    Body,
    Client,
    Method,
    Request,
    Response,
    Server,
    StatusCode,
};
use lazy_static::*;
use regex::Regex;
use serde_derive::Serialize;
use url::form_urlencoded;


use ::log::*; // external crate for macros such as debug!, info!, so on
use crate::utils;
use crate::registration;
use crate::login;

// Handler type aliases
type GenericError = Box<dyn std::error::Error + Send + Sync>;
type Result<T> = std::result::Result<T, GenericError>;

// Stand-in 404 response
static NOTFOUND: &[u8] = b"Oops! Not Found";

#[derive(Debug, Serialize)]
pub struct User {
    email: String,
    logged_in: bool,
}

lazy_static!{
    static ref SESSIONS: RwLock<HashMap<String, User>> = {
        let map = HashMap::new();
        RwLock::new(map)
    };
}

fn add_user_into_session(email: &str, logged_in: bool) -> String {
    let user = User { email: email.to_string(), logged_in: logged_in };
    let id = utils::generate_id();
    let mut sessions = SESSIONS.write().unwrap();
    debug!("add user: {:?} with session id: {:?}", &user, &id);
    sessions.insert(id.clone(), user);
    id
}

fn get_user(id: &str) -> User {
    let sessions = SESSIONS.read().unwrap();
    match sessions.get(id) {
        Some(user) => User{ email: user.email.clone(), logged_in: user.logged_in },
        None => User{email: String::new(), logged_in: false}
    }
}

fn update_user(id: String, logged_in: bool) {
    let mut user = get_user(&id);
    user.logged_in = logged_in;
    let mut sessions = SESSIONS.write().unwrap();
    sessions.remove(&id);
    sessions.insert(id, user);
}

// Routes
fn four_zero_four() -> Result<Response<Body>> {
    Ok(Response::builder()
        .status(StatusCode::NOT_FOUND)
        .body(NOTFOUND.into())
        .unwrap())
}

// Shows home page or Index page
async fn index(req: Request<Body>) -> Result<Response<Body>> {
    debug!("index( req )...............<<");
    let sid = get_session_id(&req);
    let user = get_user(&sid);  
    let mut ctx = Context::new(); // Sets up index page template rendering context
    ctx.insert("user", &user);
    let body = Body::from(super::TERA.render("index.html", &ctx).unwrap().to_string()); // Render the index template with the context
    Ok(Response::new(body))
}

// Shows Registration page
async fn registration() -> Result<Response<Body>> {
    debug!("registration()...............<<");
    let ctx = Context::new(); 
    let body = Body::from(super::TERA.render("registration.html", &ctx).unwrap().to_string());
    Ok(Response::new(body))
}

// processes submitted registration data; then shows confirm-registration page and wait for user
// confirmation
async fn add_registration_await_confirmation(req: Request<Body>) -> Result<Response<Body>> {
    debug!("add_registration_await_confirmation( req )............<<");
    let whole_body = hyper::body::to_bytes(req).await?;
    let map = form_urlencoded::parse(whole_body.as_ref())
        .into_owned()
        .collect::<HashMap<String, String>>();
    debug!("json map: {:?}", &map);
    let body_for_next_page = process_registration_data( &map );
    Ok(Response::new(body_for_next_page))
}

//fn process_registration_data(map: &serde_json::map::Map<String, serde_json::value::Value>) -> Body {
fn process_registration_data(map: &HashMap<String, String>) -> Body {
    debug!("process_registration_data( {:?} )............<<", map);
    let result = registration::Registration::from_map(map);
    let email = map.get("email").unwrap();
    let mut ctx = Context::new();
    let duration = super::app_config("token_validity_time");
    let unit = super::app_config("token_validity_unit");
    ctx.insert("duration", &duration); // after this duration, registration data will be deleted; used by client side removal logic
    ctx.insert("unit", &unit);
    ctx.insert("email", &email);
    match result {
        Ok(_msg) =>  {
            let delay = delay_into_millis(&duration, &unit);
            registration::Registration::wait_to_remove_unconfirmed(delay, email.to_string()); // server side removal logic; it is required, if the
                                                                                              // confirmation page on the browser is closed while
                                                                                              // waiting for user inputs
            Body::from(super::TERA.render("confirm-registration.html", &ctx).unwrap().to_string())
        },
        Err(msg) => {
            let err_msg = format!("Registration failed: {:?}", msg);
            Body::from(err_msg)
        }
    }
}

fn delay_into_millis(duration: &str, unit: &str) -> u64 {
    let delay: u64 = duration.parse().unwrap();
    match unit.as_ref() {
        "minutes" => delay * 60 * 1000,
        "seconds" => delay * 1000,
        _ => delay,
    }
}

async fn handle_registration_confirmation(req: Request<Body>) -> Result<Response<Body>> {
    debug!("handle_registration_confirmation({:?})..............<<", &req);
    let whole_body = hyper::body::to_bytes(req).await?;
    let map = form_urlencoded::parse(whole_body.as_ref())
        .into_owned()
        .collect::<HashMap<String, String>>();
    debug!("json map: {:?}", &map);
    let body_for_next_page = process_confirmation_data( &map );
    Ok(Response::new(body_for_next_page))
}

fn process_confirmation_data(map: &HashMap<String, String>) -> Body {
    debug!("process_confirmation_data ( {:?} ) ..............<<", map);
    // extract token from map
    let mut ctx = Context::new();
    if map.contains_key("expired") {
        let email = map.get("email").unwrap();
        let _result = registration::Registration::delete_expired_registration(&email);
        ctx.insert("status", "Registration expired! Sorry try to register again!");
        ctx.insert("show_login_link", &false);
        return Body::from(super::TERA.render("confirm-registration-status.html", &ctx).unwrap().to_string());
    }
    let token = map.get("token").unwrap();
    let result = registration::Registration::confirm(&token);
    match result {
        Ok(_msg) =>  {
            ctx.insert("status", "Registration confirmed!.");
            ctx.insert("show_login_link", &true);
            Body::from(super::TERA.render("confirm-registration-status.html", &ctx).unwrap().to_string())
        },
        Err(msg) => {
            let err_msg = format!("Registration confirmation failed: {:?}", msg);
            Body::from(err_msg)
        }
    }
}

// Shows Login page
async fn login() -> Result<Response<Body>> {
    debug!("login().....................<<");
    let mut ctx = Context::new();
    ctx.insert("has_error", &false);
    let body = Body::from(super::TERA.render("login.html", &ctx).unwrap().to_string());
    Ok(Response::new(body))
}

// login data submitted; now it shows index page with logout menu option
async fn login_submitted(req: Request<Body>) -> Result<Response<Body>> {
    debug!("login_submitted( {:?} )....................<<", &req);
    let whole_body = hyper::body::to_bytes(req).await?;
    let map = form_urlencoded::parse(whole_body.as_ref())
        .into_owned()
        .collect::<HashMap<String, String>>();
    debug!("json map: {:?}", &map);
    let response = process_login_data( &map );
    Ok(response)
}

fn process_login_data(map: &HashMap<String, String>) -> Response<Body> {
    debug!("process_login_data( {:?} )...................<<", map);
    let email = map.get("email").unwrap();
    debug!("email entered as: {:?}", &email);
    let passwd = map.get("password").unwrap();
    debug!("password entered as: {:?}", &passwd);
    match login::Login::authenticate(&email, &passwd) {
        Ok(msg) => {
            debug!("authenciated successfully: {:?}", msg);
            let logged_in = true;
            let id = add_user_into_session(&email, logged_in);
            login_success_page(&id)
        },
        Err(msg) => {
            error!("authentication failed: {:?}", msg);
            login_failed(&email)
        },
    }
}

fn login_success_page(id: &str) -> Response<Body> {
    debug!("login_success_page( {:?} )....................<<", id);
    let ctx = Context::new(); // Sets up index page template rendering context
    let body = Body::from(super::TERA.render("login-success.html", &ctx).unwrap().to_string()); // Render the index template with the context
    let sid = "sessionId=".to_owned() + id + "; PATH=/";
    Response::builder()
        .status(StatusCode::OK)
        .header(header::SET_COOKIE, sid)
        .body(body)
        .unwrap()
}

fn login_failed(email: &str) -> Response<Body> {
    debug!("login_failed( {:?} ).................<<", email);
    let mut ctx = Context::new(); 
    ctx.insert("error", &"Invalid Credentials!");
    ctx.insert("email", email);
    ctx.insert("has_error", &true);
    let body = Body::from(super::TERA.render("login.html", &ctx).unwrap().to_string());
    Response::new(body)
}

// Cancel Registration
async fn cancel_registration(req: Request<Body>) -> Result<Response<Body>> {
    debug!("cancel_registration(req).........................<<");
    let sid = get_session_id(&req);
    let user = get_user(&sid);
    let logged_in = false;
    let _user = update_user(sid, logged_in);
    let result = registration::Registration::cancel(&user.email);
    let cancelled: bool = match result {
        Ok(_msg) => true, 
        Err(msg) => { // Show error message
            debug!("cancel_registration has error: {:?}", msg);
            false
        },
    };
    let mut ctx = Context::new(); // Sets up index page template rendering context
    ctx.insert("cancelled", &cancelled);
    let body = Body::from(super::TERA.render("cancellation-status.html", &ctx).unwrap().to_string()); // Render the index template with the context
    let response = Response::builder()
        .status(StatusCode::OK)
        .body(body)
        .unwrap();
    Ok(response)
}

async fn forgot_password() -> Result<Response<Body>> { // show forgot password page to collect email id
    debug!("forgot_password(req).................<<");
    let mut ctx = Context::new();
    ctx.insert("has_error", &false);
    let body = Body::from(super::TERA.render("forgot-password.html", &ctx).unwrap().to_string());
    Ok(Response::new(body))
}

async fn forgot_password_submitted(req: Request<Body>) -> Result<Response<Body>> { // process forgot password for the given email id
    debug!("forgot_password_submitted( req )...................<<");
    let whole_body = hyper::body::to_bytes(req).await?;
    let map = form_urlencoded::parse(whole_body.as_ref())
        .into_owned()
        .collect::<HashMap<String, String>>();
    debug!("json map: {:?}", &map);
    let body_for_next_page = process_forgot_password( &map );
    Ok(Response::new(body_for_next_page))    
}

fn process_forgot_password(map: &HashMap<String, String>) -> Body {
    let email = map.get("email").unwrap();
    let duration = super::app_config("token_validity_time");
    let unit = super::app_config("token_validity_unit");    
    debug!("email entered as: {:?}", &email);
    match login::Login::forgot_password(&email) {
        Ok(msg) => {
            debug!("Successfully processed forgot password: {:?}", msg);
            let delay = delay_into_millis(&duration, &unit);
            let mut ctx = Context::new();
            ctx.insert("duration", &duration);
            ctx.insert("unit", &unit);
            ctx.insert("email", &email);
            login::Login::wait_to_expire_forgot_password_token(delay, email.to_string()); // server side expiry logic; it is required, if the
                                                                                          // confirmation page on the browser is closed while
                                                                                          // waiting for user inputs
            Body::from(super::TERA.render("confirm-forgot-password.html", &ctx).unwrap().to_string())
        },
        Err(msg) => {
            let error = format!("Email submitted failed due to: {:?}", &msg);
            let mut ctx = Context::new();
            ctx.insert("has_error", &true);
            ctx.insert("email", &email);
            ctx.insert("error", &error);
            Body::from(super::TERA.render("forgot-password.html", &ctx).unwrap().to_string())
        },
    }
}

async fn handle_forgot_password_confirmation(req: Request<Body>) -> Result<Response<Body>> {
    debug!("handle_forgot_password_confirmation(req)..............<<");
    let whole_body = hyper::body::to_bytes(req).await?;
    let map = form_urlencoded::parse(whole_body.as_ref())
        .into_owned()
        .collect::<HashMap<String, String>>();
    debug!("json map: {:?}", &map);
    let response = process_forgot_password_confirmation_data( &map );
    Ok(response)    
}

fn process_forgot_password_confirmation_data(map: &HashMap<String, String>) -> Response<Body> {
    debug!("process_confirmation_data ( {:?} ) ..............<<", map);
    // extract token from map
    let mut ctx = Context::new();
    let email = map.get("email").unwrap();
    if map.contains_key("expired") {    // Go to status page
        let _result = login::Login::forgot_password_expired(&email);
        ctx.insert("status", "Forgot password token expired! Sorry try to submit it again!");
        ctx.insert("show_login_link", &true);
        let body = Body::from(super::TERA.render("confirm-forgot-password-failed.html", &ctx).unwrap().to_string());
        Response::new(body)
    } else {
        let logged_in = false;
        let id = add_user_into_session(&email, logged_in);
        debug!("Session ID generated for forgot password: {:?} ***********************", &id);
        let body = Body::from(super::TERA.render("confirm-forgot-password-success.html", &ctx).unwrap().to_string());
        let sid = "sessionId=".to_owned() + &id + "; PATH=/";
        Response::builder()
            .status(StatusCode::OK)
            .header(header::SET_COOKIE, sid)
            .body(body)
            .unwrap()
    }
}

async fn reset_password() -> Result<Response<Body>> {
    debug!("reset_password().................<<");
    let mut ctx = Context::new();
    ctx.insert("has_error", &false);
    let body = Body::from(super::TERA.render("reset-password.html", &ctx).unwrap().to_string());
    Ok(Response::new(body))
}

async fn reset_password_submitted(req: Request<Body>) -> Result<Response<Body>> {
    debug!("reset_password_submitted(req)..............<<");
    let sid = get_session_id(&req);
    debug!("Session ID received at reset password: {:?} ~~~~~~~~~~~~~~~~~~~~~", &sid);
    let user = get_user(&sid);    
    let whole_body = hyper::body::to_bytes(req).await?;
    let map = form_urlencoded::parse(whole_body.as_ref())
        .into_owned()
        .collect::<HashMap<String, String>>();
    debug!("json map: {:?}", &map);
    let body_for_next_page = process_reset_password( &map, user.email );
    Ok(Response::new(body_for_next_page))        
}

fn process_reset_password(map: &HashMap<String, String>, email: String) -> Body {
    debug!("before calling Login::reset_password(map, email)+++++++++++++++++++++++++++");
    let result = login::Login::reset_password(map, email.clone());
    debug!("after calling Login::reset_password(map, email) with result: {:?} -------------------", &result);
    let mut ctx = Context::new();
    match result {
        Ok(_msg) =>  {
            ctx.insert("status", "Reset Password Completed!");
            ctx.insert("show_login_link", &true);
            Body::from(super::TERA.render("reset-password-status.html", &ctx).unwrap().to_string())
        },
        Err(messages) => {
            error!("{:?} occurred in process_reset_password(map, email)----------------------", &messages);
            ctx.insert("has_error", &true);         
            let err_msg = format!("Error(s): {:?}", messages);
            ctx.insert("error", &err_msg);
            Body::from(super::TERA.render("reset-password.html", &ctx).unwrap().to_string())
        }
    }    
}

// logout user and show logout page 
async fn logout(req: Request<Body>) -> Result<Response<Body>> {
    debug!("logout(req).........................<<");
    let sid = get_session_id(&req);
    let logged_in = false;
    let _user = update_user(sid, logged_in);
    let ctx = Context::new(); // Sets up index page template rendering context
    let body = Body::from(super::TERA.render("logout-success.html", &ctx).unwrap().to_string()); // Render the index template with the context
    let response = Response::builder()
        .status(StatusCode::OK)
        .body(body)
        .unwrap();
    Ok(response)
}


fn stylesheet(css: &'static str) -> Result<Response<Body>> {
    let body = Body::from(css);
    Ok(
        Response::builder()
            .status(StatusCode::OK)
            .header(header::CONTENT_TYPE, "text/css")
            .body(body)
            .unwrap(),
    )
}

fn javascript(js: &'static str) -> Result<Response<Body>> {
    let body = Body::from(js);
    Ok(
        Response::builder()
            .status(StatusCode::OK)
            .header(header::CONTENT_TYPE, "text/javascript")
            .body(body)
            .unwrap(),
    )
}

fn image(path_str: &str) -> Result<Response<Body>> {
    let path_buf = PathBuf::from(path_str);
    let file_name = path_buf.file_name().unwrap().to_str().unwrap();
    let ext = path_buf.extension().unwrap().to_str().unwrap();

    match ext {
        "svg" => {
            let body = {
                let xml = match file_name {
                    "search.svg" => include_str!("resource/search.svg"),
                    _            => "",
                };
                Body::from(xml)
            };
            Ok(
                Response::builder()
                    .status(StatusCode::OK)
                    .header(header::CONTENT_TYPE, "image/svg+xml")
                    .body(body)
                    .unwrap(),
            )
        }
        _   => four_zero_four(),
    }
}

async fn router(req: Request<Body>, _client: Client<HttpConnector>) -> Result<Response<Body>> {
    debug!("router( {:?} )......................<<", req.headers().get("host"));
    let host: &str = req.headers().get("host").unwrap().to_str().unwrap();
    let host_parts: Vec<&str> = host.split(|c| c == '.').collect();
    debug!("host parts: {:?}", host_parts);

    let sid = get_session_id(&req);
    debug!("Extracted SESSION ID: {:?}", &sid);

    debug!("Req uri path: {:?}", req.uri().path());
    debug!("Req method: {:?}", req.method());
    let uri_query = req.uri().query();
    debug!("Req URI Query {:?}", &uri_query);

    match(req.method(), req.uri().path()) { // parameters are: 1. METHOD, and 2. path
        
        (&Method::GET, "/") | (&Method::GET, "/index.html") 
            => index(req).await,

        (&Method::GET, "/registration") 
            => registration().await, // show registration page
        (&Method::POST, "/registration")  
                => add_registration_await_confirmation(req).await,
    
        (&Method::POST, "/registration-confirm-process") 
                => handle_registration_confirmation(req).await,
        
        (&Method::GET, "/static/registration.css")
                => stylesheet(include_str!("resource/registration.css")), // Style handler
        
        (&Method::GET, "/static/registration_script.js") 
                => javascript(include_str!("resource/registration_script.js")), // Script handler

        (&Method::GET, "/static/confirmation_script.js") 
                => javascript(include_str!("resource/confirmation_script.js")),

        (&Method::GET, "/login")                  
                => login().await,

        (&Method::POST, "/login")    
                => login_submitted(req).await,

        (&Method::GET, "/cancel-my-registration")
                => cancel_registration(req).await,

        (&Method::GET, "/forgot-password")
                => forgot_password().await,

        (&Method::POST, "/forgot-password")
                => forgot_password_submitted(req).await,   

        (&Method::POST, "/forgot-password-confirm-process")
                => handle_forgot_password_confirmation(req).await,

        (&Method::GET, "/reset-password")
                => reset_password().await,

        (&Method::POST, "/reset-password")
                => reset_password_submitted(req).await,

        (&Method::GET, "/static/login.css")       
                => stylesheet(include_str!("resource/login.css")), // Style handler

        (&Method::GET, "/static/login_script.js") 
                => javascript(include_str!("resource/login_script.js")), // Script handler

        (&Method::GET, "/logout")                 
                => logout(req).await, 

        (&Method::GET, "/static/logout.css")       
                => stylesheet(include_str!("resource/logout.css")), // Style handler

        (&Method::GET, path_str)                  
                => image(path_str), // Image handler 

        _       => four_zero_four(),
    }
}

pub fn get_session_id(req: &Request<Body>) -> String {
    debug!("get_session_id(req) .............................<<");
    if !req.headers().contains_key(COOKIE) {
        error!("No cookies in the header found!");
        return String::new();
    }
    debug!("Req cookie: {:?}", req.headers().get("cookie"));
    let cookies: &str = req.headers().get("cookie").unwrap().to_str().unwrap();
    let re = Regex::new(r"(^|;)sessionId=(.*)($|;)");
    let session_cookie = match re {
        Ok(expression) => expression.find(cookies),
        Err(error) => {
            error!("error occured in finding session id from cookie string: {:?}", error);
            None
        }
    };
    debug!("session cookie: {:?}", &session_cookie);
    match session_cookie {
        Some(cookie) => {
            let ids: Vec<&str> = cookie.as_str().split(|c| c == '=').collect();
            ids[1].to_string() // contains session id value
        },
        None      => String::new(),
    }
}

#[tokio::main]
pub async fn start() -> Result<()> {
    // Share a `Client` with all `Service`s
    let client = Client::new(); // create a client for all services
    let new_service = make_service_fn(move |_| {
        // Move a clone of 'client' into the `service_fn`.
        let client = client.clone();
        async {
            Ok::<_, GenericError>(service_fn(move |req| {
                // Clone again to ensure that client outlives this closure. 
                router(req, client.to_owned())
            }))
        }
    });
    let ip_address = super::app_config("ip_address"); // example: 192.168.0.234:9000
    let socket_address = ip_address.as_str().parse().unwrap(); // parse() function parses to a std::net::SocketAddr
    let server = Server::bind(&socket_address).serve(new_service);
    println!("Listening on http://{}", socket_address);
    server.await?;
    Ok(())
}