    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
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644

    use axum::http::{header::{HeaderValue,CONTENT_TYPE, HeaderMap},uri::Uri};
    use html_minifier::HTMLMinifier;
    use std::io::{ErrorKind, Result};
    use std::{
        error::Error,
        path::Path,
    //    collections::HashMap,
        str,
    };
    use tera::Context;
    use totp_rs::{Algorithm, TOTP, Secret};
    use rand::Rng;

    use crate::defs::{
    //    Config,
        AppDBs,
        ReqHeaderMap,
        UserRole,
        UserNotifyData,
        Local,
        User,
    //    AuthState,
        // UserId,
        // //    SESSION_ID,
        HELP_URI,
        HELP_EXT,
        TEMPLATE_EXT,
        TOKEN_AUTH_VALUE,
        TOKEN_KEY_VALUE,
    };
    use crate::defs::session::AuthState;

    pub struct ReqHandler<'a> {
        pub req_header: ReqHeaderMap,
        pub app_dbs: &'a AppDBs,
        pub lang: Local,
        pub uri:  &'a Uri,
        pub notify_data: UserNotifyData,
        pub auth_state: AuthState,
        pub req_name: String,
        pub context: Context,
    }

    impl<'a> ReqHandler<'a> {
        pub fn new(req_header: ReqHeaderMap, app_dbs: &'a AppDBs, uri: &'a Uri, auth_state: &'a AuthState, req_name: &str) -> Self {
            let lang = Local::get_lang(&app_dbs.config.locales,&app_dbs.config.dflt_lang, &app_dbs.config.dflt_lang);
            let ( _, notify_data) = req_header.req_user(&app_dbs);
            // dbg!("{}",&notify_data);
            let mut context = app_dbs.context.to_owned();
            context.insert("site_name",&app_dbs.config.name);
            context.insert("site_org", &app_dbs.config.org);
            context.insert("lang", &lang.itms);
            context.insert("req_name", &req_name);
            context.insert("main_url", &format!("{}://{}",&app_dbs.config.protocol, &app_dbs.config.hostport));
            context.insert("html_url", &app_dbs.config.html_url);
            context.insert("assets_url", &app_dbs.config.assets_url);
            context.insert("req_path", uri.path());
            context.insert("css_link", &app_dbs.config.ui.css_link);
            context.insert("js_link", &app_dbs.config.ui.js_link);
            context.insert("other_css_link", &app_dbs.config.ui.other_css_link);
            context.insert("other_js_link", &app_dbs.config.ui.other_js_link);
            context.insert("main_js_link", &app_dbs.config.ui.main_js_link);
            context.insert("utils_js_link", &app_dbs.config.ui.utils_js_link);
            context.insert("web_menu_items", &app_dbs.config.ui.web_menu_items);
            context.insert("usr_roles", &auth_state.user_roles());
            let user_items = User::hash_items(&auth_state.user_items());
            context.insert("usr_items", &user_items);
            context.insert("usr_name", &auth_state.user_name());
            if auth_state.is_admin() {
                context.insert("isadmin", "TRUE");
            }
            context.insert("usr_email", &auth_state.user_email());
            context.insert("session_expire", &app_dbs.config.session_expire);
            context.insert("update_session_item", &format!("{}://{}/update_item",
                &app_dbs.config.protocol, &app_dbs.config.hostport));
            let user_id = auth_state.id();
            let sid = if user_id.is_empty() || user_id == "No ID" {
                String::from("")
            } else {
                user_id.replace("-", "").to_owned()
            };
            context.insert("session_id",&sid);
            context.insert("signup_mode",&app_dbs.config.signup_mode);
            // dbg!(&services_check);
            ReqHandler {
                req_header,
                app_dbs,
                lang,
                uri,
                notify_data,
                auth_state: auth_state.to_owned(),
                req_name: req_name.to_owned(),
                context,
            }
        }
        /// Find a `md` template file under `templates_path/md/server.name/req_path` or under `templates_path/md/req_path`
        /// render if found path or return `dflt_content`
        pub fn load_md_template_file(&mut self,tpl_path: &str, tpl_file: &str, in_html: bool, dflt_content: &str) {
            let md_path = tpl_path.replace("html","md")
                .replace("txt","md");
            let md_file = tpl_file.replace(".j2",".md");
            let (md_full_path,tpl_path) = if Path::new(&format!("{}/{}{}/{}",
                &self.app_dbs.config.templates_path,
                &md_path,
                &self.app_dbs.config.name,
                &md_file
            )).exists() {
                (
                    format!("{}/{}{}/{}",
                        &self.app_dbs.config.templates_path,
                        &md_path,
                        &self.app_dbs.config.name,
                        &md_file,
                    ),
                    format!("{}{}/{}",
                        &md_path,
                        &self.app_dbs.config.name,
                        &md_file,
                    )
                )
            } else if Path::new(&format!("{}{}/{}",
                &self.app_dbs.config.templates_path,
                &md_path,
                &md_file,
            )).exists() {
                (
                    format!("{}/{}{}",
                        &self.app_dbs.config.templates_path,
                        &md_path,
                        &md_file,
                    ),
                       format!("{}{}",
                        &md_path,
                        &md_file,
                    )
                )
            } else if Path::new(&format!("{}/md/{}",
                &self.app_dbs.config.templates_path,
                &md_file,
            )).exists() {
                (
                    format!("{}/md/{}",
                        &self.app_dbs.config.templates_path,
                        &md_file,
                    ),
                       format!("md/{}",
                        &md_file,
                    )
                )
            } else {
                (String::from(""), String::from(""))
            };
            if !md_full_path.is_empty() {
                let md_content = {
                    let res = if Path::new(&md_full_path).exists() {
                        self.render_template(&tpl_path, dflt_content)
                    } else {
                        String::from("")
                    };
                    res
                    // if res.is_empty() {
                    //     std::fs::read_to_string(&md_full_path).unwrap_or(String::from(""))
                    // } else {
                    //     res
                    // }
                };
                self.context.insert("md_file", &md_file);
                //if !md_content.is_empty() {
                //     self.context.insert("md_page", format!("{} {}", &md_file.replace(".md",""),&self.app_dbs.config.name).as_str());
                //     if in_html { // self.response_in_html() {
                //         self.context.insert("page_content",Self::markdown_to_html(&md_content).as_str());
                //     } else {
                //         self.context.insert("page_content",&md_content);
                //     }
                // }
            }
        }
        pub fn template_file_dirpath(&self, tpl_file: &str) -> Result<String> {
           let tpl_path = if Path::new(&format!("{}/{}",
                &self.app_dbs.config.templates_path,
                &tpl_file
            )).exists() {
                ""
            } else if self.req_header.is_browser() && Path::new(&format!("{}/html/{}",
                &self.app_dbs.config.templates_path,
                &tpl_file
            )).exists() {
                "html/"
            } else if Path::new(&format!("{}/txt/{}",
                &self.app_dbs.config.templates_path,
                &tpl_file
            )).exists() {
                "txt/"
            } else if Path::new(&format!("{}/md/{}",
                &self.app_dbs.config.templates_path,
                &tpl_file
            )).exists() {
                "md/"
            } else {
                return Err(std::io::Error::new(
                    ErrorKind::NotFound,
                    format!("ERROR: Invalid path for {}",&tpl_file)
                ));
            };
            Ok(tpl_path.to_owned())
        }
        pub fn prepare_head_response(&self, res_header: &mut HeaderMap) {
            if self.req_header.is_browser() || self.req_header.is_wget() {
                res_header.append(axum::http::header::CONTENT_TYPE,
                    HeaderValue::try_from("text/html; charset=utf-8")
                    .expect("URI isn't a valid header value")
                );
            }
        }
        pub fn prepare_head_json_response(&self, res_header: &mut HeaderMap) {
            res_header.append(axum::http::header::CONTENT_TYPE,
                HeaderValue::try_from("application/json; charset=utf-8")
                .expect("URI isn't a valid header value")
            );
        }
        pub fn prepare_response(&mut self) {
            // self.req_header.header.contains_key(axum::http::header::CONTENT_TYPE)
            if self.req_header.is_browser() || self.req_header.is_wget() {
               self.req_header.header.append(axum::http::header::CONTENT_TYPE,
                    HeaderValue::try_from("text/html; charset=utf-8")
                    .expect("URI isn't a valid header value")
                );
            }
        }
        pub fn prepare_render(&mut self) {
            //let sid_settings = self.sid_settings(UserId::from(&self.user_id)).to_owned();
            // let session_ui_config = SessionUiConfig {
            //     token: self.has_auth_or_new(),
            //     sid: self.user_id.to_owned(),
            //     config: self.app_dbs.config.client.web_config.to_owned(),
            //     locales: self.app_dbs.config.locales.to_owned(),
            //     ui: if self.user_id.is_empty() {
            //         self.app_dbs.config.client.ui_config.to_owned()
            //     } else {
            //         sid_settings.uiconfig.to_owned()
            //     },
            //     settings: self.app_dbs.config.client.ui_settings.to_owned(),
            // };
           // self.context.insert("sid_config", &sid_settings);
            //self.context.insert("sid_config_values", &sid_settings.to_json());
            // self.context.insert("sid_ui_config", &session_ui_config);
            self.context.insert("agent",&self.req_header.agent());
        }
        pub fn load_template_file(&mut self, tpl_file: &str, dflt_content: &str) -> String {
            let tpl_file = if tpl_file.ends_with(".html") || tpl_file.ends_with(".txt") || tpl_file.ends_with(".j2") {
                tpl_file.to_owned()
            } else {
                format!("{}.j2",tpl_file)
            };
            // Madness about template path
            let (tplfile, tpl_path) = match self.template_file_dirpath(&tpl_file) {
                Ok(res) => (tpl_file.to_owned(), res),
                Err(_e) => match self.template_file_dirpath(&dflt_content) {
                    Ok(res) =>(tpl_file.to_owned(), res),
                    Err(_e) => {
                        let tplfile = format!("{}.j2",&dflt_content);
                        match self.template_file_dirpath(&tplfile) {
                            Ok(res) => (tplfile, res),
                            Err(_e)  => (tplfile, String::from(""))
                        }
                    }
                }
            };
            let template_file = if Path::new(&format!("{}/{}{}",
                &self.app_dbs.config.templates_path,
                &tpl_path,
                &tpl_file
            )).exists() {
                format!("{}{}", &tpl_path, &tplfile)
            } else {
                String::from("html/notfound.j2")
            };
            if self.app_dbs.config.verbose > 0 {
                dbg!("path: {}, file: {}, template_file: {}",&tpl_path,&tpl_file,&template_file);
            }
            self.prepare_render();
            self.context.insert("path",&tpl_file);
            self.load_md_template_file(&tpl_path, &tpl_file, tpl_path.contains("html"),"");
            self.render_template(&template_file, &dflt_content)
            // self.app_dbs.tera.render(tpl_file, &context).unwrap_or_else(|e|{
            //     println!("load template: {} errors: {}",&tpl_file,e);
            //     dflt_content.to_owned()
            // })
    /*
            if Path::new(&tpl_file).exists() {
                if let Ok(template_content) = fs::read_to_string(&tpl_file) {
                    let mut content = template_content;
                    content = self.content_replace("tpl_header", &content, "");
                    content = self.content_replace("tpl_footer", &content, "");
                    content = self.content_replace("req_name", &content, &self.req_name);
                    content = self.content_replace("logs_url", &content,
                        &format!("{}:{}",&self.app_dbs.config.protocol, &self.app_dbs.config.hostport)
                    );
                    content = self.content_replace("req_path", &content, &self.uri.path());
                    let sid = if self.user_id.is_empty() || self.user_id == "No ID" {
                       String::from("")
                    } else {
                       self.user_id.replace("-", "").to_owned()
                    };
                    content = self.content_replace("session_id", &content, &sid );
                    content = self.content_replace("token", &content, "");
                    return content
                }
            }
            println!("load template: {} not found using defaults",&tpl_file);
            dflt_content.to_owned()
    */
        }
        /*
        pub fn load_template_filename(&mut self, tpl_file: &str, dflt_content: &str) -> String {
            self.load_template_file(&format!(
                    "{}/{}.{}",
                    //"{}/{}/{}.{}",
                    //&self.app_dbs.config.templates_path,
                    self.req_header.lang(&self.app_dbs.config),
                    &tpl_file,
                    TEMPLATE_EXT
                ), dflt_content)
        }
        fn content_replace(&mut self, key: &str, content: &str, dflt_content: &str) -> String {
            let tpl_var = format!("{{{{ {} }}}}",&key);
            if content.contains(&tpl_var) {
                if key.starts_with("tpl_") {
                    content.replace(&tpl_var,self.load_template_file(
                        &format!(
                            "{}/{}/{}.{}",
                            &self.app_dbs.config.templates_path,
                            self.req_header.lang(&self.app_dbs.config),
                            &key,
                            TEMPLATE_EXT
                        ), dflt_content).as_str())
                } else {
                    content.replace(&tpl_var,dflt_content)
                }
            } else {
                content.to_owned()
            }
        }
        */
       pub fn render_template(&mut self,template_file: &str, dflt_content: &str) -> String {
            //self.check_services(None);
            self.context.insert("page", &template_file.replace(".j2","").replace("html/", "").as_str());
            if template_file.contains("md") || template_file.contains("sample") || template_file.contains("code") {
               self.context.insert("with_code", "true");
            }
            match self.app_dbs.tera.render(&template_file, &self.context) {
                Ok(s) => {
                    // println!("{:?}", s);
                    if self.req_header.is_browser() {
                        let mut html_minifier = HTMLMinifier::new();
                        match html_minifier.digest(s.as_str()) {
                            Ok(_) => {
                                let Ok(result) = str::from_utf8(html_minifier.get_html()) else { return s };
                                // let result = str::from_utf8(html_minifier.get_html()).unwrap_or(s);
                                result.to_owned()
                            },
                            Err(e) => {
                                println!("Error minifier: {}",e);
                                s
                            },
                        }
                        // match html_minifier.digest(s.as_str()) {
                        //    Ok(_) => str::from_utf8(html_minifier.get_html()).unwrap_or_default().to_owned(),
                        //    Err(e) => {
                        //     println!("Error minifier: {}",e);
                        //     s
                        //    },
                        // }
                    } else {
                       s
                    }
                },
                Err(e) => {
                    println!("Error: {}", &e);
                    let mut cause = e.source();
                    while let Some(e) = cause {
                        println!("Reason: {}", e);
                        cause = e.source();
                    }
                    dflt_content.to_owned()
                }
            }
        }
        pub fn check_request_help(&mut self) -> Option<String> {
            //dbg!(&self.uri);
            let uri_path = self.uri.path();
            if uri_path.contains(&format!("/{}",HELP_URI)) || uri_path.contains(&format!(",{}",HELP_URI)) {
                if self.req_header.is_browser() {
                      let uri = format!(
                        "{}://{}#{}?{}",
                        &self.app_dbs.config.protocol,
                        &self.app_dbs.config.hostport,
                        HELP_URI,
                        &self.req_name
                    );
                    // Pass LOCATION to header should work but JavaScript should do it also add some info
                    // if req_header.referer().contains("/html/")
                    // req_header.header.insert(LOCATION, HeaderValue::try_from(&uri).expect("URI isn't a valid header value"));
                    // dbg!(&req_header.header);
                    self.req_header.header.append(CONTENT_TYPE,
                        HeaderValue::try_from("text/html; charset=utf-8").expect("URI isn't a valid header value"));
                    // TODO load maud template for this
                    Some(
                        format!("<script>location.href='{}'</script>",&uri)
                    )
                } else {
                    Some (
                        self.load_template_file(&format!(
                            "{}/{}/{}{}.{}",
                                &self.app_dbs.config.templates_path,
                                self.req_header.lang(&self.app_dbs.config),
                                self.req_name,
                                HELP_EXT,
                                TEMPLATE_EXT
                            ),
                            &format!("{}{}",&self.req_name,HELP_EXT)
                        )
                    )
                }
            } else {
                None
            }
        }
        pub fn check_request_invalid(&mut self, name: &str) -> Option<String> {
            if let Some(help_info) = self.check_request_help() {
                return Some(help_info);
            }
            if name.len() == 0 {
                let lang = self.req_header.lang(&self.app_dbs.config);
                let (tpl_file, dflt_msg) = if self.req_header.is_browser() {
                    // TODO load template for this
                    self.req_header.header.append(CONTENT_TYPE,
                        HeaderValue::try_from("text/html; charset=utf-8").expect("URI isn't a valid header value"));
                    (
                        format!("{}/{}_invalid.html",&self.app_dbs.config.templates_path,&lang),
                        format!("<h2>invalid path</h2>")
                    )
                } else {
                    (
                        format!("{}/{}/invalid.{}",&self.app_dbs.config.templates_path,&lang,TEMPLATE_EXT),
                        format!("invalid path"),
                    )
                };
                Some(self.load_template_file(&tpl_file, &dflt_msg))
            } else {
                None
            }
        }
        pub fn check_request_auth(&mut self, _url_pathname: &str) -> Option<String> {
            if let Some(help_info) = self.check_request_help() {
                return Some(help_info);
            }
            // dbg!(self.req_header.auth());
            let user_id = self.auth_state.id();
            if self.req_header.auth().is_empty() && (user_id.is_empty() || user_id == "No ID") {
                let msg = "No Authorization found";
                self.context.insert("page_content", &msg);
                if let Some(tpl) = self.app_dbs.config.tpls.get("noauth") {
                    Some(
                        self.response_tpl_msg(tpl,  &msg)
                    )
                } else {
                    Some( msg.to_owned())
                }
                // if self.req_header.is_browser() && self.req_header.internal().is_empty() {
                //     let uri = format!(
                //         "{}://{}{}",
                //         &self.app_dbs.config.protocol,
                //         &self.app_dbs.config.hostport,
                //         &url_pathname
                //     );
                //     // Pass LOCATION to header should work but JavaScript should do it also add some info
                //     // if req_header.referer().contains("/html/")
                //     // req_header.header.insert(LOCATION, HeaderValue::try_from(&uri).expect("URI isn't a valid header value"));
                //     // dbg!(&req_header.header);
                //     self.req_header.header.append(CONTENT_TYPE,
                //         HeaderValue::try_from("text/html; charset=utf-8").expect("URI isn't a valid header value"));

                //     Some(
                //             // TODO load template for this
                //             // format!("<script>location.href='{}'</script>",&uri)
                //         )
                // } else {
                //     Some(
                //         self.load_template_file(&format!(
                //                 "{}/{}/request_no_auth.{}",
                //                 &self.app_dbs.config.templates_path,
                //                 self.req_header.lang(&self.app_dbs.config.server),
                //                 TEMPLATE_EXT
                //             ),
                //             "invalid request auth")
                //     )
                // }
            } else {
                None
            }
        }
        pub fn bad_request(&mut self,msg: &str) -> String {

            if let Some(tpl) = self.app_dbs.config.tpls.get("notfound") {
                self.response_tpl_msg(tpl, msg)
            } else {
                msg.to_owned()
            }
        }
        pub fn response_tpl_msg(&mut self, tpl:& str, msg: &str) -> String {
            self.prepare_response();
            let root_tpl = if self.req_header.is_browser() {
                "html"
            } else {
                "txt"
            };
            self.context.insert("page_content", &msg);
            self.load_template_file(&format!("{}/{}",&root_tpl,&tpl), &msg)
        }
        pub fn auth_role(&self) -> UserRole {
            #[cfg(feature = "authstore")]
            if let Some(authz) =  self.app_dbs.auth_store.authz.get(&self.notify_data.auth) {
                println!("aut: {}, name: {}, role: {}",&self.notify_data.auth, &authz.name,&authz.role);
                authz.role.to_owned()
            } else {
                UserRole::Anonymous
            }
            #[cfg(feature = "casbin")]
            UserRole::Anonymous
        }
        pub fn get_config_lang(&self) -> Local {
           Local::get_lang(&self.app_dbs.config.locales,&self.app_dbs.config.dflt_lang,&self.app_dbs.config.dflt_lang)
        }
        pub fn get_lang(&self, key: &str) -> Local {
           Local::get_lang(&self.app_dbs.config.locales, key, &self.app_dbs.config.dflt_lang)
        }
        // pub fn sid_settings(&mut self, op_user_id: Option<UserId> ) -> SidSettings {
        //     if let Some(user_id) = op_user_id {
        //         let sid_settings = user_id.sid_settings(&self.app_dbs.sessions_config);
        //         if sid_settings.lang != self.lang.id {
        //             self.lang = self.get_lang(&sid_settings.lang);
        //         }
        //         sid_settings
        //     } else {
        //         self.app_dbs.sessions_config.sid_settings.to_owned()
        //     }
        // }
        pub fn new_token(&self) -> String {
            let user_notify_data = UserNotifyData {
                id: format!("{}",self.auth_state.id()),
                auth: TOKEN_AUTH_VALUE.to_owned(),
                key: TOKEN_KEY_VALUE.to_owned(),
            };
            user_notify_data.token(&self.app_dbs.config, &self.app_dbs.config.paseto, false)
        }
        pub fn has_auth_or_new(&self) -> String {
            if self.req_header.auth().is_empty() {
                self.new_token()
            } else {
                self.req_header.auth()
            }
        }
        pub fn otp_make(&self, code: &str, defs: &str) -> Result<TOTP>  {
            let secret = match Secret::Encoded(code.to_owned()).to_bytes() {
                Ok(scrt) => scrt,
                Err(e) =>
                    return Err(std::io::Error::new(
                    ErrorKind::NotFound,
                    format!("ERROR: Invalid Secret {}",&e)
                    ))
            };
            let (digits, str_algorithm) = if defs.is_empty() {
                (   self.app_dbs.config.totp_digits,
                    format!("{}",self.app_dbs.config.totp_algorithm)
                )
            } else {
                let arr_defs = defs.split(",").collect::<Vec<&str>>();
                if arr_defs.len() > 1 {
                    (   arr_defs[0].parse().unwrap_or(self.app_dbs.config.totp_digits),
                        arr_defs[1].to_owned()
                    )
                } else {
                    (   self.app_dbs.config.totp_digits,
                        format!("{}",self.app_dbs.config.totp_algorithm)
                    )
                }
            };
            let algorithm = match str_algorithm.to_uppercase().as_str() {
                "SHA1" => Algorithm::SHA1,
                "SHA256" => Algorithm::SHA256,
                "SHA512" => Algorithm::SHA512,
                _ => Algorithm::SHA1,
            };
            let totp = match TOTP::new(
                algorithm,
                digits,
                1,
                30,
                secret,
                Some(format!("{}",self.app_dbs.config.name)),
                format!("{}",self.app_dbs.config.org)
            ) {
                Ok(totp) => totp,
                Err(e) =>
                    return Err(std::io::Error::new(
                    ErrorKind::NotFound,
                    format!("ERROR: Invalid Topt {}",&e)
                    ))
            };
            Ok(totp)
        }
        pub fn otp_generate(&self) -> Result<TOTP> {
            let mut rng = rand::thread_rng();
            let data_byte: [u8; 21] = rng.gen();
            let base32_string = base32::encode(base32::Alphabet::RFC4648 { padding: false }, &data_byte);
            match self.otp_make(&base32_string, "") {
                Ok(totp) => Ok(totp),
                Err(e) =>
                    Err(std::io::Error::new(
                    ErrorKind::NotFound,
                    format!("ERROR: Invalid TOTP {}",&e)
                    ))
            }
        }
        pub fn otp_check(&self, code: &str, token: &str, defs: &str) -> Result<bool> {
            let totp = match self.otp_make(code, defs) {
                Ok(totp) => totp,
                Err(e) =>
                    return Err(std::io::Error::new(
                    ErrorKind::NotFound,
                    format!("ERROR: Invalid TOTP {}",&e)
                    ))
            };
            match totp.check_current(&token) {
                Ok(result) => Ok(result),
                Err(e) =>
                    return Err(std::io::Error::new(
                    ErrorKind::NotFound,
                    format!("ERROR: check {}",&e)
                    ))
            }
        }
    }