diff --git a/src/users/permissions.rs b/src/users/permissions.rs index 78ff463..2a0e804 100644 --- a/src/users/permissions.rs +++ b/src/users/permissions.rs @@ -3,6 +3,7 @@ use sqlx::PgConnection; use crate::{database::DatabaseError, users::User}; /// Infradmin and systemuser have all permissions. +#[derive(strum::IntoStaticStr)] pub enum Permission { // All Users have the right to observe their own sessions ListOthersSessions, @@ -16,26 +17,41 @@ pub enum Permission { CreateTags, RenameTags, DeleteTags, - #[allow(unused)] + CreateQuotes, DeleteQuotes, ChangePersonPrimaryName, - #[allow(unused)] BrowseServerLogs, ConfigureInstance, } +impl Permission { + pub fn is_default_permission(&self) -> bool { + match self { + Self::CreateTags | Self::CreateQuotes => true, + _ => false, + } + } +} + impl User { pub async fn has_permission( &self, - #[allow(unused)] conn: &mut PgConnection, - #[allow(unused)] permission: Permission, + conn: &mut PgConnection, + permission: Permission, ) -> Result { - // Infradmin and systemuser have all permissions if self.is_infradmin() || self.is_systemuser() { return Ok(true); } - Ok(false) - // todo!("Do the permission checking here once permissions are modeled in the DB") + let permission_key: &'static str = (&permission).into(); + let state: Option = sqlx::query_scalar( + "SELECT state FROM user_permissions WHERE user_id = $1 AND permission = $2", + ) + .bind(self.id) + .bind(permission_key) + .fetch_optional(&mut *conn) + .await?; + + Ok(state.unwrap_or_else(|| permission.is_default_permission())) } }