laravel-two-factor-rust 0.3.0

Laravel Two Factor for Rust: authenticator app codes, QR codes and recovery codes for Laravel for Rust
Documentation
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};

/// One-time codes a user keeps for when their phone is gone. Each code logs in once.
///
/// Store them encrypted, as `Encrypted<Vec<String>>`, and show them to the user once.
///
/// ```
/// use laravel_two_factor::RecoveryCodes;
///
/// let mut codes = RecoveryCodes::generate(8);
/// let first = codes[0].clone();
///
/// assert!(RecoveryCodes::redeem(&mut codes, &first));
/// assert!(!RecoveryCodes::redeem(&mut codes, &first));
/// assert_eq!(codes.len(), 8);
/// ```
#[derive(Clone, Copy, Debug)]
pub struct RecoveryCodes;

impl RecoveryCodes {
    /// `count` new codes, each two groups of ten random letters and digits, such as
    /// `x8Rk2QpL0a-Vb7Tz1MnE4c`.
    ///
    /// # Panics
    ///
    /// Panics when the operating system can't provide random bytes.
    #[must_use]
    pub fn generate(count: usize) -> Vec<String> {
        (0..count).map(|_| Self::code()).collect()
    }

    /// Whether `code` is one of `codes`, replacing it with a new one if so. Surrounding spaces are
    /// ignored.
    ///
    /// # Panics
    ///
    /// Panics when the operating system can't provide random bytes.
    pub fn redeem(codes: &mut [String], code: &str) -> bool {
        let code = code.trim();
        // Constant time, so the time taken doesn't tell which code matched.
        let mut found = Choice::from(0);
        let mut matched = 0;

        for (index, candidate) in (0u64..).zip(codes.iter()) {
            let equal = candidate.as_bytes().ct_eq(code.as_bytes());
            matched.conditional_assign(&index, equal);
            found |= equal;
        }

        if !bool::from(found) {
            return false;
        }

        codes[usize::try_from(matched).expect("an index into the codes")] = Self::code();
        true
    }

    fn code() -> String {
        format!("{}-{}", laravel::str::random(10), laravel::str::random(10))
    }
}