autter-core 2.0.2

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

impl DataManager {
    /// Get an [`AuditLogEntry`] from an SQL row.
    pub(crate) fn get_audit_log_entry_from_row(x: &PostgresRow) -> AuditLogEntry {
        AuditLogEntry {
            id: Id::deserialize(&get!(x->0(String))),
            created: get!(x->1(i64)) as u128,
            moderator: Id::Legacy(get!(x->2(i64)) as usize),
            content: get!(x->3(String)),
        }
    }

    auto_method!(get_audit_log_entry_by_id(usize as i64)@get_audit_log_entry_from_row -> "SELECT * FROM a_audit_log WHERE id = $1" --name="audit log entry" --returns=AuditLogEntry --cache-key-tmpl="srmp.audit_log:{}");

    /// Get all audit log entries (paginated).
    ///
    /// # Arguments
    /// * `batch` - the limit of items in each page
    /// * `page` - the page number
    pub async fn get_audit_log_entries(
        &self,
        batch: usize,
        page: usize,
    ) -> Result<Vec<AuditLogEntry>> {
        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_audit_log ORDER BY created DESC LIMIT $1 OFFSET $2",
            &[&(batch as i64), &((page * batch) as i64)],
            |x| { Self::get_audit_log_entry_from_row(x) }
        );

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

        Ok(res.unwrap())
    }

    /// Create a new audit log entry in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`AuditLogEntry`] object to insert
    pub async fn create_audit_log_entry(&self, data: AuditLogEntry) -> Result<()> {
        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_audit_log VALUES ($1, $2, $3, $4)",
            params![
                &data.id.printable(),
                &(data.created as i64),
                &(data.moderator.as_usize() as i64),
                &data.content.as_str(),
            ]
        );

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

        // return
        Ok(())
    }

    pub async fn delete_audit_log_entry(&self, id: &Id, user: User) -> Result<()> {
        if !user.permissions.contains(&UserPermission::ManageAuditLog) {
            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_audit_log WHERE id = $1",
            &[&id.printable()]
        );

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

        self.0.1.remove(format!("srmp.audit_log:{}", id)).await;

        // return
        Ok(())
    }
}