use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use totp_rs::{Algorithm, Builder as TotpBuilder};
use super::TotpHandler;
impl TotpHandler {
fn check_now(now: i64) -> GarrisonResult<u64> {
u64::try_from(now)
.map_err(|_| GarrisonError::InvalidParam("secure-totp-negative-now::".to_string()))
}
pub fn new(secret: Vec<u8>, step: u64, digits: u32) -> GarrisonResult<Self> {
Self::new_with_hash_algorithm(secret, step, digits, Algorithm::SHA1)
}
pub fn new_with_hash_algorithm(
secret: Vec<u8>,
step: u64,
digits: u32,
algorithm: Algorithm,
) -> GarrisonResult<Self> {
let totp = TotpBuilder::new()
.with_algorithm(algorithm)
.with_digits(digits as u8)
.with_skew(1) .with_step_duration(step)
.with_secret(secret)
.build()
.map_err(|e| GarrisonError::Internal(format!("secure-totp-init::{}", e)))?;
Ok(Self { totp, step })
}
pub fn generate(&self, now: i64) -> GarrisonResult<String> {
let now = Self::check_now(now)?;
Ok(self.totp.generate(now).to_string())
}
pub fn validate(&self, code: &str, now: i64) -> GarrisonResult<bool> {
let now = Self::check_now(now)?;
Ok(self.totp.check(code, now).is_some())
}
pub async fn validate_and_consume(
&self,
login_id: &str,
code: &str,
now: i64,
dao: &dyn GarrisonDao,
) -> GarrisonResult<bool> {
let now = Self::check_now(now)?;
if self.totp.check(code, now).is_none() {
return Ok(false);
}
let replay_key = format!("totp:used:{}:{}", login_id, code);
let ttl = self
.step
.checked_mul(3)
.ok_or_else(|| GarrisonError::Internal("secure-totp-ttl-overflow::".to_string()))?;
let count = dao.incr(&replay_key, ttl).await?;
Ok(count == 1)
}
pub fn secret_from_base32(s: &str) -> GarrisonResult<Vec<u8>> {
base32::decode(base32::Alphabet::Rfc4648 { padding: false }, s).ok_or_else(|| {
GarrisonError::Internal(format!("secure-base32-decode::secret_len={}", s.len()))
})
}
}