    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
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    850
    851
    852
    853
    854
    855
    856
    857
    858
    859
    860
    861
    862
    863
    864
    865
    866
    867
    868
    869
    870
    871
    872
    873
    874
    875
    876
    877
    878
    879
    880
    881
    882
    883
    884
    885
    886
    887
    888
    889
    890
    891
    892
    893
    894
    895
    896
    897
    898
    899
    900
    901
    902
    903
    904
    905
    906
    907
    908
    909
    910
    911
    912
    913
    914
    915
    916
    917
    918
    919
    920
    921
    922
    923
    924
    925
    926
    927
    928
    929
    930
    931
    932
    933
    934
    935
    936
    937
    938
    939
    940
    941
    942
    943
    944
    945
    946
    947
    948
    949
    950
    951
    952
    953
    954
    955
    956
    957
    958
    959
    960
    961
    962
    963
    964
    965

    /*
     * Copyright (C) 2022  Aravinth Manivannan <realaravinth@batsense.net>
     *
     * This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU Affero General Public License as
     * published by the Free Software Foundation, either version 3 of the
     * License, or (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU Affero General Public License for more details.
     *
     * You should have received a copy of the GNU Affero General Public License
     * along with this program.  If not, see <https://www.gnu.org/licenses/>.
     */
    use std::str::FromStr;

    use db_core::dev::*;

    use sqlx::mysql::MySqlPoolOptions;
    use sqlx::types::time::OffsetDateTime;
    use sqlx::ConnectOptions;
    use sqlx::MySqlPool;

    pub mod errors;
    #[cfg(test)]
    pub mod tests;

    #[derive(Clone)]
    pub struct Database {
        pub pool: MySqlPool,
    }

    /// Use an existing database pool
    pub struct Conn(pub MySqlPool);

    /// Connect to database
    pub enum ConnectionOptions {
        /// fresh connection
        Fresh(Fresh),
        /// existing connection
        Existing(Conn),
    }

    pub struct Fresh {
        pub pool_options: MySqlPoolOptions,
        pub disable_logging: bool,
        pub url: String,
    }

    pub mod dev {
        pub use super::errors::*;
        pub use super::Database;
        pub use db_core::dev::*;
        pub use prelude::*;
        pub use sqlx::Error;
    }

    pub mod prelude {
        pub use super::*;
        pub use db_core::prelude::*;
    }

    #[async_trait]
    impl Connect for ConnectionOptions {
        type Pool = Database;
        async fn connect(self) -> DBResult<Self::Pool> {
            let pool = match self {
                Self::Fresh(fresh) => {
                    let mut connect_options =
                        sqlx::mysql::MySqlConnectOptions::from_str(&fresh.url).unwrap();
                    if fresh.disable_logging {
                        connect_options.disable_statement_logging();
                    }
                    sqlx::mysql::MySqlConnectOptions::from_str(&fresh.url)
                        .unwrap()
                        .disable_statement_logging();
                    fresh
                        .pool_options
                        .connect_with(connect_options)
                        .await
                        .map_err(|e| DBError::DBError(Box::new(e)))?
                }

                Self::Existing(conn) => conn.0,
            };
            Ok(Database { pool })
        }
    }

    use dev::*;

    #[async_trait]
    impl Migrate for Database {
        async fn migrate(&self) -> DBResult<()> {
            sqlx::migrate!("./migrations/")
                .run(&self.pool)
                .await
                .map_err(|e| DBError::DBError(Box::new(e)))?;
            Ok(())
        }
    }

    #[async_trait]
    impl MCDatabase for Database {
        /// ping DB
        async fn ping(&self) -> bool {
            use sqlx::Connection;

            if let Ok(mut con) = self.pool.acquire().await {
                con.ping().await.is_ok()
            } else {
                false
            }
        }

        /// register a new user
        async fn register(&self, p: &Register) -> DBResult<()> {
            let res = if let Some(email) = &p.email {
                sqlx::query!(
                    "insert into mcaptcha_users
            (name , password, email, secret) values (?, ?, ?, ?)",
                    &p.username,
                    &p.hash,
                    &email,
                    &p.secret,
                )
                .execute(&self.pool)
                .await
            } else {
                sqlx::query!(
                    "INSERT INTO mcaptcha_users
            (name , password,  secret) VALUES (?, ?, ?)",
                    &p.username,
                    &p.hash,
                    &p.secret,
                )
                .execute(&self.pool)
                .await
            };
            res.map_err(map_register_err)?;
            Ok(())
        }

        /// delete a user
        async fn delete_user(&self, username: &str) -> DBResult<()> {
            sqlx::query!("DELETE FROM mcaptcha_users WHERE name = (?)", username)
                .execute(&self.pool)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;
            Ok(())
        }

        /// check if username exists
        async fn username_exists(&self, username: &str) -> DBResult<bool> {
            match sqlx::query!("SELECT name from mcaptcha_users WHERE name = ?", username,)
                .fetch_one(&self.pool)
                .await
            {
                Ok(_) => Ok(true),
                Err(sqlx::Error::RowNotFound) => Ok(false),
                Err(e) => Err(map_register_err(e)),
            }
        }

        /// get user email
        async fn get_email(&self, username: &str) -> DBResult<Option<String>> {
            struct Email {
                email: Option<String>,
            }

            let res = sqlx::query_as!(
                Email,
                "SELECT email FROM mcaptcha_users WHERE name = ?",
                username
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;
            Ok(res.email)
        }

        /// check if email exists
        async fn email_exists(&self, email: &str) -> DBResult<bool> {
            match sqlx::query!("SELECT name from mcaptcha_users WHERE email = ?", email)
                .fetch_one(&self.pool)
                .await
            {
                Ok(_) => Ok(true),
                Err(sqlx::Error::RowNotFound) => Ok(false),
                Err(e) => Err(map_register_err(e)),
            }
        }

        /// update a user's email
        async fn update_email(&self, p: &UpdateEmail) -> DBResult<()> {
            sqlx::query!(
                "UPDATE mcaptcha_users set email = ?
                WHERE name = ?",
                &p.new_email,
                &p.username,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(())
        }

        /// get a user's password
        async fn get_password(&self, l: &Login) -> DBResult<NameHash> {
            struct Password {
                name: String,
                password: String,
            }

            let rec = match l {
                Login::Username(u) => sqlx::query_as!(
                    Password,
                    r#"SELECT name, password  FROM mcaptcha_users WHERE name = ?"#,
                    u,
                )
                .fetch_one(&self.pool)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?,

                Login::Email(e) => sqlx::query_as!(
                    Password,
                    r#"SELECT name, password  FROM mcaptcha_users WHERE email = ?"#,
                    e,
                )
                .fetch_one(&self.pool)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?,
            };

            let res = NameHash {
                hash: rec.password,
                username: rec.name,
            };

            Ok(res)
        }

        /// update user's password
        async fn update_password(&self, p: &NameHash) -> DBResult<()> {
            sqlx::query!(
                "UPDATE mcaptcha_users set password = ?
                WHERE name = ?",
                &p.hash,
                &p.username,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(())
        }

        /// update username
        async fn update_username(&self, current: &str, new: &str) -> DBResult<()> {
            sqlx::query!(
                "UPDATE mcaptcha_users set name = ?
                WHERE name = ?",
                new,
                current,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(())
        }

        /// get a user's secret
        async fn get_secret(&self, username: &str) -> DBResult<Secret> {
            let secret = sqlx::query_as!(
                Secret,
                r#"SELECT secret  FROM mcaptcha_users WHERE name = ?"#,
                username,
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(secret)
        }

        /// get a user's secret from a captcha key
        async fn get_secret_from_captcha(&self, key: &str) -> DBResult<Secret> {
            let secret = sqlx::query_as!(
                Secret,
                r#"SELECT secret  FROM mcaptcha_users WHERE ID = (
                        SELECT user_id FROM mcaptcha_config WHERE captcha_key = ?
                        )"#,
                key,
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(secret)
        }

        /// update a user's secret
        async fn update_secret(&self, username: &str, secret: &str) -> DBResult<()> {
            sqlx::query!(
                "UPDATE mcaptcha_users set secret = ?
            WHERE name = ?",
                &secret,
                &username,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(())
        }

        /// create new captcha
        async fn create_captcha(&self, username: &str, p: &CreateCaptcha) -> DBResult<()> {
            sqlx::query!(
                "INSERT INTO mcaptcha_config
            (`captcha_key`, `user_id`, `duration`, `name`)
            VALUES (?, (SELECT ID FROM mcaptcha_users WHERE name = ?), ?, ?)",
                p.key,
                username,
                p.duration as i32,
                p.description,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            Ok(())
        }

        /// Get captcha config
        async fn get_captcha_config(&self, username: &str, key: &str) -> DBResult<Captcha> {
            let captcha = sqlx::query_as!(
                InternaleCaptchaConfig,
                "SELECT `config_id`, `duration`, `name`, `captcha_key` from mcaptcha_config WHERE
                            `captcha_key` = ? AND
                            user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?) ",
                &key,
                &username,
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(captcha.into())
        }

        /// Get all captchas belonging to user
        async fn get_all_user_captchas(&self, username: &str) -> DBResult<Vec<Captcha>> {
            let mut res = sqlx::query_as!(
                InternaleCaptchaConfig,
                "SELECT captcha_key, name, config_id, duration FROM mcaptcha_config WHERE
                user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?) ",
                &username,
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            let mut captchas = Vec::with_capacity(res.len());

            res.drain(0..).for_each(|r| captchas.push(r.into()));

            Ok(captchas)
        }

        /// update captcha metadata; doesn't change captcha key
        async fn update_captcha_metadata(
            &self,
            username: &str,
            p: &CreateCaptcha,
        ) -> DBResult<()> {
            sqlx::query!(
                "UPDATE mcaptcha_config SET name = ?, duration = ?
                WHERE user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?)
                AND captcha_key = ?",
                p.description,
                p.duration,
                username,
                p.key,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(())
        }

        /// update captcha key; doesn't change metadata
        async fn update_captcha_key(
            &self,
            username: &str,
            old_key: &str,
            new_key: &str,
        ) -> DBResult<()> {
            sqlx::query!(
                "UPDATE mcaptcha_config SET captcha_key = ?
            WHERE captcha_key = ? AND user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?)",
                new_key,
                old_key,
                username,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(())
        }

        /// Add levels to captcha
        async fn add_captcha_levels(
            &self,
            username: &str,
            captcha_key: &str,
            levels: &[Level],
        ) -> DBResult<()> {
            use futures::future::try_join_all;
            let mut futs = Vec::with_capacity(levels.len());

            for level in levels.iter() {
                let difficulty_factor = level.difficulty_factor as i32;
                let visitor_threshold = level.visitor_threshold as i32;
                let fut = sqlx::query!(
                    "INSERT INTO mcaptcha_levels (
                difficulty_factor,
                visitor_threshold,
                config_id) VALUES  (
                ?, ?, (
                    SELECT config_id FROM mcaptcha_config WHERE
                    captcha_key = (?) AND user_id = (
                    SELECT ID FROM mcaptcha_users WHERE name = ?
                        )));",
                    difficulty_factor,
                    visitor_threshold,
                    &captcha_key,
                    username,
                )
                .execute(&self.pool);
                futs.push(fut);
            }

            try_join_all(futs)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(())
        }

        /// check if captcha exists
        async fn captcha_exists(
            &self,
            username: Option<&str>,
            captcha_key: &str,
        ) -> DBResult<bool> {
            //        let mut exists = false;

            #[allow(dead_code)]
            struct ConfigId {
                config_id: i32,
            }
            let res = match username {
                Some(username) => {
                    sqlx::query_as!(
                        ConfigId,
                        "SELECT config_id FROM mcaptcha_config
                            WHERE
                                captcha_key = ?
                            AND user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?)",
                        captcha_key,
                        username
                    )
                    .fetch_one(&self.pool)
                    .await
                    //                if let Some(x) = x.exists {
                    //                    exists = x;
                    //                };
                }

                None => {
                    sqlx::query_as!(
                        ConfigId,
                        "SELECT config_id from mcaptcha_config WHERE captcha_key = ?",
                        &captcha_key,
                    )
                    .fetch_one(&self.pool)
                    .await
                } //if let Some(x) = x.exists {
                  //    exists = x;
                  //};
            };
            match res {
                Ok(_) => Ok(true),
                Err(sqlx::Error::RowNotFound) => Ok(false),
                Err(e) => Err(map_register_err(e)),
            }
        }

        /// Delete all levels of a captcha
        async fn delete_captcha_levels(
            &self,
            username: &str,
            captcha_key: &str,
        ) -> DBResult<()> {
            sqlx::query!(
                "DELETE FROM mcaptcha_levels
            WHERE config_id = (
                SELECT config_id FROM mcaptcha_config where captcha_key= (?)
                AND user_id = (
                SELECT ID from mcaptcha_users WHERE name = ?
                )
                )",
                captcha_key,
                username
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(())
        }

        /// Delete captcha
        async fn delete_captcha(&self, username: &str, captcha_key: &str) -> DBResult<()> {
            sqlx::query!(
                "DELETE FROM mcaptcha_config where captcha_key= (?)
                    AND
                user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?)",
                captcha_key,
                username,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(())
        }

        /// Get captcha levels
        async fn get_captcha_levels(
            &self,
            username: Option<&str>,
            captcha_key: &str,
        ) -> DBResult<Vec<Level>> {
            struct I32Levels {
                difficulty_factor: i32,
                visitor_threshold: i32,
            }
            let levels = match username {
                None => sqlx::query_as!(
                    I32Levels,
                    "SELECT difficulty_factor, visitor_threshold FROM mcaptcha_levels  WHERE
                config_id = (
                    SELECT config_id FROM mcaptcha_config where captcha_key= (?)
                    ) ORDER BY difficulty_factor ASC;",
                    captcha_key,
                )
                .fetch_all(&self.pool)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?,

                Some(username) => sqlx::query_as!(
                    I32Levels,
                    "SELECT difficulty_factor, visitor_threshold FROM mcaptcha_levels  WHERE
                config_id = (
                    SELECT config_id FROM mcaptcha_config where captcha_key= (?)
                    AND user_id = (SELECT ID from mcaptcha_users WHERE name = ?)
                    )
                ORDER BY difficulty_factor ASC;",
                    captcha_key,
                    username
                )
                .fetch_all(&self.pool)
                .await
                .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?,
            };

            let mut new_levels = Vec::with_capacity(levels.len());
            for l in levels.iter() {
                new_levels.push(Level {
                    difficulty_factor: l.difficulty_factor as u32,
                    visitor_threshold: l.visitor_threshold as u32,
                });
            }
            Ok(new_levels)
        }

        /// Get captcha's cooldown period
        async fn get_captcha_cooldown(&self, captcha_key: &str) -> DBResult<i32> {
            struct DurationResp {
                duration: i32,
            }

            let resp = sqlx::query_as!(
                DurationResp,
                "SELECT duration FROM mcaptcha_config
                where captcha_key= ?",
                captcha_key,
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(resp.duration)
        }
        /// Add traffic configuration
        async fn add_traffic_pattern(
            &self,
            username: &str,
            captcha_key: &str,
            pattern: &TrafficPattern,
        ) -> DBResult<()> {
            sqlx::query!(
                "INSERT INTO mcaptcha_sitekey_user_provided_avg_traffic (
                config_id,
                avg_traffic,
                peak_sustainable_traffic,
                broke_my_site_traffic
                ) VALUES (
                 (SELECT config_id FROM mcaptcha_config where captcha_key= (?)
                 AND user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?)
                ), ?, ?, ?)",
                //payload.avg_traffic,
                captcha_key,
                username,
                pattern.avg_traffic as i32,
                pattern.peak_sustainable_traffic as i32,
                pattern.broke_my_site_traffic.as_ref().map(|v| *v as i32),
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;
            Ok(())
        }

        /// Get traffic configuration
        async fn get_traffic_pattern(
            &self,
            username: &str,
            captcha_key: &str,
        ) -> DBResult<TrafficPattern> {
            struct Traffic {
                peak_sustainable_traffic: i32,
                avg_traffic: i32,
                broke_my_site_traffic: Option<i32>,
            }
            let res = sqlx::query_as!(
                Traffic,
                "SELECT
              avg_traffic,
              peak_sustainable_traffic,
              broke_my_site_traffic
            FROM
              mcaptcha_sitekey_user_provided_avg_traffic
            WHERE
              config_id = (
                SELECT
                  config_id
                FROM
                  mcaptcha_config
                WHERE
                  captcha_key = ?
                  AND user_id = (
                    SELECT
                      id
                    FROM
                      mcaptcha_users
                    WHERE
                      NAME = ?
                  )
              )
            ",
                captcha_key,
                username
            )
            .fetch_one(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::TrafficPatternNotFound))?;
            Ok(TrafficPattern {
                broke_my_site_traffic: res.broke_my_site_traffic.as_ref().map(|v| *v as u32),
                avg_traffic: res.avg_traffic as u32,
                peak_sustainable_traffic: res.peak_sustainable_traffic as u32,
            })
        }

        /// Delete traffic configuration
        async fn delete_traffic_pattern(
            &self,
            username: &str,
            captcha_key: &str,
        ) -> DBResult<()> {
            sqlx::query!(
                "DELETE FROM mcaptcha_sitekey_user_provided_avg_traffic
            WHERE config_id = (
                SELECT config_id
                FROM
                    mcaptcha_config
                WHERE
                    captcha_key = ?
                AND
                    user_id = (SELECT ID FROM mcaptcha_users WHERE name = ?)
                );",
                captcha_key,
                username,
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::TrafficPatternNotFound))?;
            Ok(())
        }

        /// create new notification
        async fn create_notification(&self, p: &AddNotification) -> DBResult<()> {
            let now = now_unix_time_stamp();
            sqlx::query!(
                "INSERT INTO mcaptcha_notifications (
                  heading, message, tx, rx, received)
                  VALUES  (
                  ?, ?,
                      (SELECT ID FROM mcaptcha_users WHERE name = ?),
                      (SELECT ID FROM mcaptcha_users WHERE name = ?),
                      ?
                          );",
                p.heading,
                p.message,
                p.from,
                p.to,
                now
            )
            .execute(&self.pool)
            .await
            .map_err(map_register_err)?;

            Ok(())
        }

        /// get all unread notifications
        async fn get_all_unread_notifications(
            &self,
            username: &str,
        ) -> DBResult<Vec<Notification>> {
            let mut inner_notifications = sqlx::query_file_as!(
                InnerNotification,
                "./src/get_all_unread_notifications.sql",
                &username
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::AccountNotFound))?;

            let mut notifications = Vec::with_capacity(inner_notifications.len());

            inner_notifications
                .drain(0..)
                .for_each(|n| notifications.push(n.into()));

            Ok(notifications)
        }

        /// mark a notification read
        async fn mark_notification_read(&self, username: &str, id: i32) -> DBResult<()> {
            sqlx::query_file_as!(
                Notification,
                "./src/mark_notification_read.sql",
                id,
                &username
            )
            .execute(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::NotificationNotFound))?;

            Ok(())
        }

        /// record PoWConfig fetches
        async fn record_fetch(&self, key: &str) -> DBResult<()> {
            let now = now_unix_time_stamp();
            let _ = sqlx::query!(
            "INSERT INTO mcaptcha_pow_fetched_stats
            (config_id, time) VALUES ((SELECT config_id FROM mcaptcha_config where captcha_key= ?), ?)",
            key,
            &now,
        )
        .execute(&self.pool)
        .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;
            Ok(())
        }

        /// record PoWConfig solves
        async fn record_solve(&self, key: &str) -> DBResult<()> {
            let now = OffsetDateTime::now_utc();
            let _ = sqlx::query!(
            "INSERT INTO mcaptcha_pow_solved_stats
            (config_id, time) VALUES ((SELECT config_id FROM mcaptcha_config where captcha_key= ?), ?)",
            key,
            &now,
        )
        .execute(&self.pool)
        .await
        .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;
            Ok(())
        }

        /// record PoWConfig confirms
        async fn record_confirm(&self, key: &str) -> DBResult<()> {
            let now = now_unix_time_stamp();
            let _ = sqlx::query!(
            "INSERT INTO mcaptcha_pow_confirmed_stats
            (config_id, time) VALUES ((SELECT config_id FROM mcaptcha_config where captcha_key= ?), ?)",
            key,
            &now
        )
        .execute(&self.pool)
        .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;
            Ok(())
        }

        /// fetch PoWConfig fetches
        async fn fetch_config_fetched(&self, user: &str, key: &str) -> DBResult<Vec<i64>> {
            let records = sqlx::query_as!(
                Date,
                "SELECT time FROM mcaptcha_pow_fetched_stats
                WHERE
                    config_id = (
                        SELECT
                            config_id FROM mcaptcha_config
                        WHERE
                            captcha_key = ?
                        AND
                            user_id = (
                            SELECT
                                ID FROM mcaptcha_users WHERE name = ?))
                    ORDER BY time DESC",
                &key,
                &user,
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(Date::dates_to_unix(records))
        }

        /// fetch PoWConfig solves
        async fn fetch_solve(&self, user: &str, key: &str) -> DBResult<Vec<i64>> {
            let records = sqlx::query_as!(
                Date,
                "SELECT time FROM mcaptcha_pow_solved_stats
                WHERE config_id = (
                    SELECT config_id FROM mcaptcha_config
                    WHERE
                        captcha_key = ?
                    AND
                         user_id = (
                            SELECT
                                ID FROM mcaptcha_users WHERE name = ?))
                    ORDER BY time DESC",
                &key,
                &user
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(Date::dates_to_unix(records))
        }

        /// fetch PoWConfig confirms
        async fn fetch_confirm(&self, user: &str, key: &str) -> DBResult<Vec<i64>> {
            let records = sqlx::query_as!(
                Date,
                "SELECT time FROM mcaptcha_pow_confirmed_stats
                WHERE
                    config_id = (
                        SELECT config_id FROM mcaptcha_config
                    WHERE
                        captcha_key = ?
                    AND
                         user_id = (
                            SELECT
                                ID FROM mcaptcha_users WHERE name = ?))
                    ORDER BY time DESC",
                &key,
                &user
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| map_row_not_found_err(e, DBError::CaptchaNotFound))?;

            Ok(Date::dates_to_unix(records))
        }
    }

    #[derive(Clone)]
    struct Date {
        time: OffsetDateTime,
    }

    impl Date {
        fn dates_to_unix(mut d: Vec<Self>) -> Vec<i64> {
            let mut dates = Vec::with_capacity(d.len());
            d.drain(0..)
                .for_each(|x| dates.push(x.time.unix_timestamp()));
            dates
        }
    }

    fn now_unix_time_stamp() -> OffsetDateTime {
        OffsetDateTime::now_utc()
    }

    #[derive(Debug, Clone, PartialEq)]
    /// Represents notification
    pub struct InnerNotification {
        /// receiver name  of the notification
        pub name: String,
        /// heading of the notification
        pub heading: String,
        /// message of the notification
        pub message: String,
        /// when notification was received
        pub received: OffsetDateTime,
        /// db assigned ID of the notification
        pub id: i32,
    }

    impl From<InnerNotification> for Notification {
        fn from(n: InnerNotification) -> Self {
            Notification {
                name: Some(n.name),
                heading: Some(n.heading),
                message: Some(n.message),
                received: Some(n.received.unix_timestamp()),
                id: Some(n.id),
            }
        }
    }

    #[derive(Clone)]
    struct InternaleCaptchaConfig {
        config_id: i32,
        duration: i32,
        name: String,
        captcha_key: String,
    }

    impl From<InternaleCaptchaConfig> for Captcha {
        fn from(i: InternaleCaptchaConfig) -> Self {
            Self {
                config_id: i.config_id,
                duration: i.duration,
                description: i.name,
                key: i.captcha_key,
            }
        }
    }