use crate::constants::DaoKeyPrefix;
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::strategy::firewall::{FirewallContext, GarrisonFirewallStrategy, StrategyRegistration};
use async_trait::async_trait;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use super::{LockoutState, UserLockoutConfig, UserLockoutStrategy, WaitStrategy};
impl Default for UserLockoutConfig {
fn default() -> Self {
Self {
max_failure_factor: 5,
permanent_lockout: true,
max_temporary_lockouts: 3,
wait_strategy: WaitStrategy::Multiple {
base_seconds: 60,
multiplier: 2,
},
failure_window_seconds: 300,
}
}
}
pub(super) fn now_timestamp() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
fn calculate_lock_seconds(strategy: &WaitStrategy, n: u32) -> u64 {
let n = n.max(1);
match strategy {
WaitStrategy::Multiple {
base_seconds,
multiplier,
} => *base_seconds * (*multiplier as u64).pow(n - 1),
WaitStrategy::Linear { base_seconds } => *base_seconds * n as u64,
}
}
impl UserLockoutStrategy {
pub fn new(config: UserLockoutConfig, dao: Arc<dyn GarrisonDao>) -> Self {
Self {
config,
dao,
#[cfg(feature = "metrics-prometheus")]
metrics: None,
}
}
#[cfg(feature = "metrics-prometheus")]
pub fn with_metrics(mut self, metrics: Arc<crate::account::metrics::AccountMetrics>) -> Self {
self.metrics = Some(metrics);
self
}
pub(super) async fn get_state(&self, user_id: &str) -> GarrisonResult<LockoutState> {
let key = DaoKeyPrefix::Lockout.build_key(user_id);
match self.dao.get(&key).await? {
Some(json) => serde_json::from_str(&json)
.map_err(|e| GarrisonError::Dao(format!("account-lockout-deserialize::{}", e))),
None => Ok(LockoutState::default()),
}
}
pub(super) async fn set_state(
&self,
user_id: &str,
state: &LockoutState,
) -> GarrisonResult<()> {
let key = DaoKeyPrefix::Lockout.build_key(user_id);
let json = serde_json::to_string(state)
.map_err(|e| GarrisonError::Dao(format!("account-lockout-serialize::{}", e)))?;
self.dao.set(&key, &json, 0).await
}
pub async fn record_failure(&self, user_id: &str) -> GarrisonResult<()> {
let mut state = self.get_state(user_id).await?;
let now = now_timestamp();
match state.first_failure_at {
Some(first_at) => {
let window = self.config.failure_window_seconds as i64;
if now - first_at > window {
state.failure_count = 0;
state.first_failure_at = Some(now);
}
},
None => {
state.first_failure_at = Some(now);
},
}
state.failure_count += 1;
if state.failure_count >= self.config.max_failure_factor {
if self.config.permanent_lockout
&& state.temporary_lockout_count + 1 > self.config.max_temporary_lockouts
{
state.permanent_locked = true;
#[cfg(feature = "metrics-prometheus")]
if let Some(metrics) = &self.metrics {
metrics.record_lockout(true);
}
} else {
state.temporary_lockout_count += 1;
let lock_seconds = calculate_lock_seconds(
&self.config.wait_strategy,
state.temporary_lockout_count,
);
state.locked_until = now_timestamp() + lock_seconds as i64;
#[cfg(feature = "metrics-prometheus")]
if let Some(metrics) = &self.metrics {
metrics.record_lockout(false);
}
}
}
self.set_state(user_id, &state).await
}
pub async fn record_success(&self, user_id: &str) -> GarrisonResult<()> {
let mut state = self.get_state(user_id).await?;
state.failure_count = 0;
state.first_failure_at = None;
self.set_state(user_id, &state).await
}
pub async fn unlock(&self, user_id: &str) -> GarrisonResult<()> {
let state = LockoutState::default();
self.set_state(user_id, &state).await
}
}
#[async_trait]
impl GarrisonFirewallStrategy for UserLockoutStrategy {
async fn check(&self, ctx: &FirewallContext) -> GarrisonResult<()> {
let user_id = match &ctx.login_id {
Some(id) => id.as_str(),
None => return Ok(()),
};
let state = self.get_state(user_id).await?;
if state.permanent_locked {
return Err(GarrisonError::FirewallBlocked(format!(
"user-lockout: 用户 {} 已被永久锁定",
user_id
)));
}
let now = now_timestamp();
if state.locked_until > now {
return Err(GarrisonError::FirewallBlocked(format!(
"user-lockout: 用户 {} 已被临时锁定,直到 {}",
user_id, state.locked_until
)));
}
Ok(())
}
}
inventory::submit! {
StrategyRegistration {
name: "user-lockout",
}
}