autter-core 2.0.2

Autter authentication service for Shrimpcamp
Documentation
use crate::{
    DataManager,
    model::{Error, Result, User, UserPermission, organizations::PermissionsList},
};
use oiseau::{PostgresRow, cache::Cache, execute, get, params, query_rows};
use tetratto_core2::{auto_method, model::id::Id};

impl DataManager {
    /// Get a [`PermissionsList`] from an SQL row.
    pub(crate) fn get_permissions_list_from_row(x: &PostgresRow) -> PermissionsList {
        PermissionsList {
            id: Id::deserialize(&get!(x->0(String))),
            created: get!(x->1(i64)) as u128,
            owner_org: Id::deserialize(&get!(x->2(String))),
            name: get!(x->3(String)),
            roles: serde_json::from_str(&get!(x->4(String))).unwrap(),
        }
    }

    auto_method!(get_permissions_list_by_id()@get_permissions_list_from_row -> "SELECT * FROM a_permissions_lists WHERE id = $1" --name="permissions_list" --returns=PermissionsList --cache-key-tmpl="srmp.permissions_list:{}");

    /// Get all permissions_lists by organization (paginated).
    ///
    /// # Arguments
    /// * `organization` - the ID of the user to fetch permissions_lists for
    pub async fn get_permissions_lists_by_organization(
        &self,
        organization: &Id,
        batch: usize,
        page: usize,
    ) -> Result<Vec<PermissionsList>> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM a_permissions_lists WHERE owner_org = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
            &[
                &organization.printable(),
                &(batch as i64),
                &((page * batch) as i64)
            ],
            |x| { Self::get_permissions_list_from_row(x) }
        );

        if res.is_err() {
            return Err(Error::GeneralNotFound("permissions_list".to_string()));
        }

        Ok(res.unwrap())
    }

    /// Create a new permissions_list in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`PermissionsList`] object to insert
    pub async fn create_permissions_list(&self, data: PermissionsList) -> Result<Id> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(
            &conn,
            "INSERT INTO a_permissions_lists VALUES ($1, $2, $3, $4, $5)",
            params![
                &data.id.printable(),
                &(data.created as i64),
                &data.owner_org.printable(),
                &data.name,
                &serde_json::to_string(&data.roles).unwrap()
            ]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        // return
        Ok(data.id)
    }

    pub async fn delete_permissions_list(&self, id: &Id, user: User) -> Result<()> {
        let permissions_list = self.get_permissions_list_by_id(&id).await?;
        let org = self
            .get_organization_by_id(&permissions_list.owner_org)
            .await?;

        if user.id != org.owner
            && !user
                .permissions
                .contains(&UserPermission::ManageOrganizations)
        {
            return Err(Error::NotAllowed);
        }

        // ...
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = execute!(
            &conn,
            "DELETE FROM a_permissions_lists WHERE id = $1",
            &[&id.printable()]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        self.0
            .1
            .remove(format!("srmp.permissions_list:{}", id))
            .await;

        // return
        Ok(())
    }

    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:{}");
}