couchdb_orm/client/couchdb/actions/db/secure/
mod.rs

1// Copyright (C) 2020-2023  OpenToolAdd
2//
3// This program is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with this program.  If not, see <http://www.gnu.org/licenses/>.
15// contact: contact@tool-add.com
16
17use crate::client::couchdb::models::Security;
18use crate::regexes::COUCHDB_DB_RULE;
19use awc::Client;
20
21pub mod errors;
22
23use errors::DBSecureError;
24
25pub async fn secure_db(
26    client: &Client,
27    db_name: &str,
28    data: Security,
29    host: &str,
30) -> Result<bool, Box<dyn std::error::Error>> {
31    if !COUCHDB_DB_RULE.is_match(db_name) {
32        return Err(Box::new(DBSecureError::new(&format!(
33            "{} string doesn't respect the regex rule {}",
34            db_name,
35            COUCHDB_DB_RULE.as_str()
36        ))));
37    }
38
39    // println!("{:?}", db_status);
40    let uri: String = format!("{}/{}/_security", host, db_name,);
41    // println!("{:?}", serde_json::to_string(&data).unwrap());
42    match client.put(&uri).send_json(&data).await {
43        Ok(mut response) => {
44            // println!("{:?}", response);
45            if response.status().as_u16() >= 400 {
46                let bytes: Vec<u8> = response.body().await?.iter().cloned().collect();
47                let error: serde_json::Value =
48                    serde_json::from_str(std::str::from_utf8(bytes.as_slice()).unwrap()).unwrap();
49                Err(Box::new(DBSecureError::new(&format!(
50                    "Error with the request to {}: error: \n{}",
51                    &uri, error
52                ))))
53            } else {
54                Ok(true)
55            }
56        }
57        Err(error) => Err(Box::new(DBSecureError::new(&format!(
58            "Error with the request to {}: error: \n{}",
59            host, error
60        )))),
61    }
62}
63
64#[cfg(test)]
65mod tests {}