use std::time::{SystemTime, UNIX_EPOCH};
use crate::error::RoleError;
#[derive(Debug, Clone)]
pub struct TimedRoleDelegation {
pub from_role: String,
pub to_role: String,
pub valid_until: u64,
pub conditions: Vec<DelegationCondition>,
}
#[derive(Debug, Clone)]
pub enum DelegationCondition {
TimeRange { start: u64, end: u64 },
RequireApproval { approver_role: String },
MaxUsageCount(u32),
}
impl TimedRoleDelegation {
pub fn new(from_role: &str, to_role: &str, duration_secs: u64) -> Self {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
Self {
from_role: from_role.to_string(),
to_role: to_role.to_string(),
valid_until: now + duration_secs,
conditions: Vec::new(),
}
}
pub fn add_condition(&mut self, condition: DelegationCondition) {
self.conditions.push(condition);
}
pub fn is_valid(&self) -> Result<bool, RoleError> {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
if now > self.valid_until {
return Ok(false);
}
for condition in &self.conditions {
match condition {
DelegationCondition::TimeRange { start, end } => {
if now < *start || now > *end {
return Ok(false);
}
}
DelegationCondition::RequireApproval { .. } => {
}
DelegationCondition::MaxUsageCount(count) => {
if *count == 0 {
return Ok(false);
}
}
}
}
Ok(true)
}
}