Skip to content
Clone
f0a1552
54 lines 1.3 KB Rust
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use models::admin::admin_user::AdminRole;
use uuid::Uuid;
use crate::errors::AdminApiError;
use crate::errors::AdminError;
#[derive(Debug, Clone)]
pub struct AdminActor {
pub id: Uuid,
pub username: String,
pub display_name: String,
pub role: AdminRole,
pub must_change_password: bool,
}
impl AdminActor {
pub fn level(role: AdminRole) -> u8 {
match role {
AdminRole::SuperAdmin => 3,
AdminRole::Operator => 2,
AdminRole::Viewer => 1,
}
}
pub fn is_super(&self) -> bool {
matches!(self.role, AdminRole::SuperAdmin)
}
pub fn require(&self, minimum: AdminRole) -> Result<(), AdminError> {
if Self::level(self.role) >= Self::level(minimum) {
Ok(())
} else {
Err(AdminError::Forbidden)
}
}
}
#[derive(Debug, Clone)]
pub struct CurrentAdmin(pub AdminActor);
impl<S: Send + Sync> FromRequestParts<S> for CurrentAdmin {
type Rejection = AdminApiError;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
parts
.extensions
.get::<AdminActor>()
.cloned()
.map(CurrentAdmin)
.ok_or_else(AdminApiError::unauthorized)
}
}