cyaxon_authifier/impl/mfa/
mod.rs

1use crate::{
2	models::{totp::Totp, MFAMethod, MFAResponse, MultiFactorAuthentication},
3	Error, Result, Success,
4};
5
6mod totp;
7
8impl MultiFactorAuthentication {
9	// Check whether MFA is in-use
10	pub fn is_active(&self) -> bool {
11		matches!(self.totp_token, Totp::Enabled { .. })
12	}
13
14	// Check whether there are still usable recovery codes
15	pub fn has_recovery(&self) -> bool {
16		!self.recovery_codes.is_empty()
17	}
18
19	// Get available MFA methods
20	pub fn get_methods(&self) -> Vec<MFAMethod> {
21		if let Totp::Enabled { .. } = self.totp_token {
22			let mut methods = vec![MFAMethod::Totp];
23
24			if self.has_recovery() {
25				methods.push(MFAMethod::Recovery);
26			}
27
28			methods
29		} else {
30			vec![MFAMethod::Password]
31		}
32	}
33
34	// Generate new recovery codes
35	pub fn generate_recovery_codes(&mut self) {
36		static ALPHABET: [char; 32] = [
37			'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
38			'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z',
39		];
40
41		let mut codes = vec![];
42		for _ in 1..=10 {
43			codes.push(format!(
44				"{}-{}",
45				nanoid!(5, &ALPHABET),
46				nanoid!(5, &ALPHABET)
47			));
48		}
49
50		self.recovery_codes = codes;
51	}
52
53	// Generate new TOTP secret
54	pub fn generate_new_totp_secret(&mut self) -> Result<String> {
55		if let Totp::Enabled { .. } = self.totp_token {
56			return Err(Error::OperationFailed);
57		}
58
59		let secret: [u8; 10] = rand::random();
60		let secret = base32::encode(base32::Alphabet::RFC4648 { padding: false }, &secret);
61
62		self.totp_token = Totp::Pending {
63			secret: secret.clone(),
64		};
65
66		Ok(secret)
67	}
68
69	/// Enable TOTP using a given MFA response
70	pub fn enable_totp(&mut self, response: MFAResponse) -> Success {
71		if let MFAResponse::Totp { totp_code } = response {
72			let code = self.totp_token.generate_code()?;
73
74			if code == totp_code {
75				let mut totp = Totp::Disabled;
76				std::mem::swap(&mut totp, &mut self.totp_token);
77
78				if let Totp::Pending { secret } = totp {
79					self.totp_token = Totp::Enabled { secret };
80
81					Ok(())
82				} else {
83					Err(Error::OperationFailed)
84				}
85			} else {
86				Err(Error::InvalidToken)
87			}
88		} else {
89			Err(Error::InvalidToken)
90		}
91	}
92}