autter_core/database/
permissions_lists.rs

1use crate::{
2    DataManager,
3    model::{Error, Result, User, UserPermission, organizations::PermissionsList},
4};
5use oiseau::{PostgresRow, cache::Cache, execute, get, params, query_rows};
6use tetratto_core::auto_method;
7
8impl DataManager {
9    /// Get a [`PermissionsList`] from an SQL row.
10    pub(crate) fn get_permissions_list_from_row(x: &PostgresRow) -> PermissionsList {
11        PermissionsList {
12            id: get!(x->0(i64)) as usize,
13            created: get!(x->1(i64)) as usize,
14            owner_org: get!(x->2(i64)) as usize,
15            name: get!(x->3(String)),
16            roles: serde_json::from_str(&get!(x->4(String))).unwrap(),
17        }
18    }
19
20    auto_method!(get_permissions_list_by_id(usize as i64)@get_permissions_list_from_row -> "SELECT * FROM a_permissions_lists WHERE id = $1" --name="permissions_list" --returns=PermissionsList --cache-key-tmpl="srmp.permissions_list:{}");
21
22    /// Get all permissions_lists by organization (paginated).
23    ///
24    /// # Arguments
25    /// * `organization` - the ID of the user to fetch permissions_lists for
26    pub async fn get_permissions_lists_by_organization(
27        &self,
28        organization: usize,
29        batch: usize,
30        page: usize,
31    ) -> Result<Vec<PermissionsList>> {
32        let conn = match self.0.connect().await {
33            Ok(c) => c,
34            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
35        };
36
37        let res = query_rows!(
38            &conn,
39            "SELECT * FROM a_permissions_lists WHERE owner_org = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
40            &[
41                &(organization as i64),
42                &(batch as i64),
43                &((page * batch) as i64)
44            ],
45            |x| { Self::get_permissions_list_from_row(x) }
46        );
47
48        if res.is_err() {
49            return Err(Error::GeneralNotFound("permissions_list".to_string()));
50        }
51
52        Ok(res.unwrap())
53    }
54
55    /// Create a new permissions_list in the database.
56    ///
57    /// # Arguments
58    /// * `data` - a mock [`PermissionsList`] object to insert
59    pub async fn create_permissions_list(&self, data: PermissionsList) -> Result<usize> {
60        let conn = match self.0.connect().await {
61            Ok(c) => c,
62            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
63        };
64
65        let res = execute!(
66            &conn,
67            "INSERT INTO a_permissions_lists VALUES ($1, $2, $3, $4, $5)",
68            params![
69                &(data.id as i64),
70                &(data.created as i64),
71                &(data.owner_org as i64),
72                &data.name,
73                &serde_json::to_string(&data.roles).unwrap()
74            ]
75        );
76
77        if let Err(e) = res {
78            return Err(Error::DatabaseError(e.to_string()));
79        }
80
81        // return
82        Ok(data.id)
83    }
84
85    pub async fn delete_permissions_list(&self, id: usize, user: User) -> Result<()> {
86        let permissions_list = self.get_permissions_list_by_id(id).await?;
87        let org = self
88            .get_organization_by_id(permissions_list.owner_org)
89            .await?;
90
91        if user.id != org.owner
92            && !user
93                .permissions
94                .contains(&UserPermission::ManageOrganizations)
95        {
96            return Err(Error::NotAllowed);
97        }
98
99        // ...
100        let conn = match self.0.connect().await {
101            Ok(c) => c,
102            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
103        };
104
105        let res = execute!(
106            &conn,
107            "DELETE FROM a_permissions_lists WHERE id = $1",
108            &[&(id as i64)]
109        );
110
111        if let Err(e) = res {
112            return Err(Error::DatabaseError(e.to_string()));
113        }
114
115        self.0
116            .1
117            .remove(format!("srmp.permissions_list:{}", id))
118            .await;
119
120        // return
121        Ok(())
122    }
123
124    auto_method!(update_permissions_list_roles(Vec<usize>) -> "UPDATE a_permissions_lists SET roles = $1 WHERE id = $2" --serde --cache-key-tmpl="srmp.permissions_list:{}");
125}