use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use totp_rs::{Algorithm, TOTP};
use super::TotpHandler;
impl TotpHandler {
pub fn new(secret: Vec<u8>, step: u64, digits: u32) -> GarrisonResult<Self> {
let totp = TOTP::new(
Algorithm::SHA1,
digits as usize,
1, step,
secret,
)
.map_err(|e| GarrisonError::Internal(format!("secure-totp-init::{}", e)))?;
Ok(Self { totp, step })
}
pub fn generate(&self, now: i64) -> String {
self.totp.generate(now as u64)
}
pub fn validate(&self, code: &str, now: i64) -> bool {
self.totp.check(code, now as u64)
}
pub async fn validate_and_consume(
&self,
login_id: &str,
code: &str,
now: i64,
dao: &dyn GarrisonDao,
) -> GarrisonResult<bool> {
if !self.totp.check(code, now as u64) {
return Ok(false);
}
let replay_key = format!("totp:used:{}:{}", login_id, code);
let count = dao.incr(&replay_key, self.step * 3).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::{}", s)))
}
}