      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

    /*
    * Copyright (C) 2021  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 actix_identity::Identity;
    use actix_web::{post, web, HttpResponse, Responder};
    use m_captcha::{defense::Level, DefenseBuilder};
    use serde::{Deserialize, Serialize};

    use super::is_authenticated;
    use crate::api::v1::mcaptcha::mcaptcha::MCaptchaDetails;
    use crate::errors::*;
    use crate::Data;

    #[derive(Serialize, Deserialize)]
    pub struct AddLevels {
        pub levels: Vec<Level>,
        // name is config_name
        pub key: String,
    }

    // TODO try for non-existent token names

    #[post("/api/v1/mcaptcha/levels/add")]
    pub async fn add_levels(
        payload: web::Json<AddLevels>,
        data: web::Data<Data>,
        id: Identity,
    ) -> ServiceResult<impl Responder> {
        is_authenticated(&id)?;
        let mut defense = DefenseBuilder::default();
        let username = id.identity().unwrap();

        for level in payload.levels.iter() {
            defense.add_level(level.clone())?;
        }

        defense.build()?;

        for level in payload.levels.iter() {
            let difficulty_factor = level.difficulty_factor as i32;
            let visitor_threshold = level.visitor_threshold as i32;
            sqlx::query!(
                "INSERT INTO mcaptcha_levels (
                difficulty_factor,
                visitor_threshold,
                config_id) VALUES  (
                $1, $2, (
                    SELECT config_id FROM mcaptcha_config WHERE
                    key = ($3) AND user_id = (
                    SELECT ID FROM mcaptcha_users WHERE name = $4
                        )));",
                difficulty_factor,
                visitor_threshold,
                &payload.key,
                &username,
            )
            .execute(&data.db)
            .await?;
        }

        Ok(HttpResponse::Ok())
    }

    #[post("/api/v1/mcaptcha/levels/update")]
    pub async fn update_levels(
        payload: web::Json<AddLevels>,
        data: web::Data<Data>,
        id: Identity,
    ) -> ServiceResult<impl Responder> {
        is_authenticated(&id)?;
        let username = id.identity().unwrap();
        let mut defense = DefenseBuilder::default();

        for level in payload.levels.iter() {
            defense.add_level(level.clone())?;
        }

        // I feel this is necessary as both difficulty factor _and_ visitor threshold of a
        // level could change so doing this would not require us to send level_id to client
        // still, needs to be benchmarked
        defense.build()?;

        sqlx::query!(
            "DELETE FROM mcaptcha_levels
            WHERE config_id = (
                SELECT config_id FROM mcaptcha_config where key = ($1)
                AND user_id = (
                SELECT ID from mcaptcha_users WHERE name = $2
                )
                )",
            &payload.key,
            &username
        )
        .execute(&data.db)
        .await?;

        for level in payload.levels.iter() {
            let difficulty_factor = level.difficulty_factor as i32;
            let visitor_threshold = level.visitor_threshold as i32;
            sqlx::query!(
                "INSERT INTO mcaptcha_levels (
                difficulty_factor,
                visitor_threshold,
                config_id) VALUES  (
                $1, $2, (
                        SELECT config_id FROM mcaptcha_config WHERE key = ($3) AND
                        user_id = (
                            SELECT ID from mcaptcha_users WHERE name = $4
                        )
                    ));",
                difficulty_factor,
                visitor_threshold,
                &payload.key,
                &username,
            )
            .execute(&data.db)
            .await?;
        }

        Ok(HttpResponse::Ok())
    }

    #[post("/api/v1/mcaptcha/levels/delete")]
    pub async fn delete_levels(
        payload: web::Json<AddLevels>,
        data: web::Data<Data>,
        id: Identity,
    ) -> ServiceResult<impl Responder> {
        is_authenticated(&id)?;
        let username = id.identity().unwrap();

        for level in payload.levels.iter() {
            let difficulty_factor = level.difficulty_factor as i32;
            sqlx::query!(
                "DELETE FROM mcaptcha_levels  WHERE
                config_id = (
                    SELECT config_id FROM mcaptcha_config WHERE key = $1 AND
                     user_id = (SELECT ID from mcaptcha_users WHERE name = $3)
                    ) AND difficulty_factor = ($2);",
                &payload.key,
                difficulty_factor,
                &username
            )
            .execute(&data.db)
            .await?;
        }

        Ok(HttpResponse::Ok())
    }

    #[post("/api/v1/mcaptcha/levels/get")]
    pub async fn get_levels(
        payload: web::Json<MCaptchaDetails>,
        data: web::Data<Data>,
        id: Identity,
    ) -> ServiceResult<impl Responder> {
        is_authenticated(&id)?;
        let username = id.identity().unwrap();

        let levels = get_levels_util(&payload.key, &username, &data).await?;

        Ok(HttpResponse::Ok().json(levels))
    }

    #[derive(Clone, Debug, Deserialize, Serialize)]
    pub struct Levels {
        levels: I32Levels,
    }

    #[derive(Clone, Debug, Deserialize, Serialize)]
    pub struct I32Levels {
        pub difficulty_factor: i32,
        pub visitor_threshold: i32,
    }

    async fn get_levels_util(key: &str, username: &str, data: &Data) -> ServiceResult<Vec<I32Levels>> {
        let levels = sqlx::query_as!(
            I32Levels,
            "SELECT difficulty_factor, visitor_threshold FROM mcaptcha_levels  WHERE
                config_id = (
                    SELECT config_id FROM mcaptcha_config WHERE key = ($1)
                    AND user_id = (SELECT ID from mcaptcha_users WHERE name = $2)
                    );",
            key,
            &username
        )
        .fetch_all(&data.db)
        .await?;

        Ok(levels)
    }

    #[cfg(test)]
    mod tests {
        use actix_web::http::{header, StatusCode};
        use actix_web::test;

        use super::*;
        use crate::tests::*;
        use crate::*;

        #[actix_rt::test]
        async fn level_routes_work() {
            const NAME: &str = "testuserlevelroutes";
            const PASSWORD: &str = "longpassworddomain";
            const EMAIL: &str = "testuserlevelrouts@a.com";
            const UPDATE_URL: &str = "/api/v1/mcaptcha/levels/update";
            const DEL_URL: &str = "/api/v1/mcaptcha/levels/delete";
            const GET_URL: &str = "/api/v1/mcaptcha/levels/get";

            {
                let data = Data::new().await;
                delete_user(NAME, &data).await;
            }

            register_and_signin(NAME, EMAIL, PASSWORD).await;
            let (data, _, signin_resp, key) = add_levels_util(NAME, PASSWORD).await;
            let cookies = get_cookie!(signin_resp);
            let mut app = get_app!(data).await;
            /*

            let add_level = AddLevels {
                levels: levels.clone(),
                key: key.key.clone(),
            };

            // 1. add level
            let add_token_resp = test::call_service(
                &mut app,
                post_request!(&add_level, ADD_URL)
                    .cookie(cookies.clone())
                    .to_request(),
            )
            .await;
            assert_eq!(add_token_resp.status(), StatusCode::OK);
            */

            // 2. get level

            let levels = vec![L1, L2];

            let get_level_resp = test::call_service(
                &mut app,
                post_request!(&key, GET_URL)
                    .cookie(cookies.clone())
                    .to_request(),
            )
            .await;
            assert_eq!(get_level_resp.status(), StatusCode::OK);
            let res_levels: Vec<Level> = test::read_body_json(get_level_resp).await;
            assert_eq!(res_levels, levels);

            // 3. update level

            let l1 = Level {
                difficulty_factor: 10,
                visitor_threshold: 10,
            };
            let l2 = Level {
                difficulty_factor: 5000,
                visitor_threshold: 5000,
            };
            let levels = vec![l1, l2];
            let add_level = AddLevels {
                levels: levels.clone(),
                key: key.key.clone(),
            };
            let add_token_resp = test::call_service(
                &mut app,
                post_request!(&add_level, UPDATE_URL)
                    .cookie(cookies.clone())
                    .to_request(),
            )
            .await;
            assert_eq!(add_token_resp.status(), StatusCode::OK);
            let get_level_resp = test::call_service(
                &mut app,
                post_request!(&key, GET_URL)
                    .cookie(cookies.clone())
                    .to_request(),
            )
            .await;
            assert_eq!(get_level_resp.status(), StatusCode::OK);
            let res_levels: Vec<Level> = test::read_body_json(get_level_resp).await;
            assert_eq!(res_levels, levels);

            // 4. delete level
            let l1 = Level {
                difficulty_factor: 10,
                visitor_threshold: 10,
            };
            let l2 = Level {
                difficulty_factor: 5000,
                visitor_threshold: 5000,
            };
            let levels = vec![l1, l2];
            let add_level = AddLevels {
                levels: levels.clone(),
                key: key.key.clone(),
            };
            let add_token_resp = test::call_service(
                &mut app,
                post_request!(&add_level, DEL_URL)
                    .cookie(cookies.clone())
                    .to_request(),
            )
            .await;
            assert_eq!(add_token_resp.status(), StatusCode::OK);
            let get_level_resp = test::call_service(
                &mut app,
                post_request!(&key, GET_URL)
                    .cookie(cookies.clone())
                    .to_request(),
            )
            .await;
            assert_eq!(get_level_resp.status(), StatusCode::OK);
            let res_levels: Vec<Level> = test::read_body_json(get_level_resp).await;
            assert_eq!(res_levels, Vec::new());
        }
    }