Skip to main content

authnz_common/types/
totp.rs

1#[cfg(any(feature = "app-server-types", feature = "authnz-server-types"))]
2use impulse_server_kit::salvo;
3#[cfg(any(feature = "app-server-types", feature = "authnz-server-types"))]
4use salvo::oapi::ToSchema;
5use serde::{Deserialize, Serialize};
6
7#[derive(Deserialize, Serialize, PartialEq, Eq, Hash, Clone, Debug, Default)]
8#[cfg_attr(any(feature = "app-server-types", feature = "authnz-server-types"), derive(ToSchema))]
9#[serde(rename_all = "snake_case", tag = "type")]
10/// TOTP algorithm.
11pub enum TOTPAlgorithm {
12  #[default]
13  /// SHA1 algorithm.
14  Sha1,
15  /// SHA2-256 algorithm.
16  Sha256,
17  /// SHA2-512 algorithm.
18  Sha512,
19}
20
21impl TOTPAlgorithm {
22  /// Converts string to algorithm.
23  /// Panics if `alg` is not in the list: `SHA1`, `SHA256`, `SHA512`.
24  pub fn from_unchecked(alg: &str) -> Self {
25    match alg {
26      "SHA1" => Self::Sha1,
27      "SHA256" => Self::Sha256,
28      "SHA512" => Self::Sha512,
29      _ => unreachable!(),
30    }
31  }
32
33  /// Converts to `authnz_totp::Algorithm`.
34  pub fn into_totp_rs(&self) -> authnz_totp::Algorithm {
35    match self {
36      Self::Sha1 => authnz_totp::Algorithm::SHA1,
37      Self::Sha256 => authnz_totp::Algorithm::SHA256,
38      Self::Sha512 => authnz_totp::Algorithm::SHA512,
39    }
40  }
41}
42
43impl std::fmt::Display for TOTPAlgorithm {
44  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45    match self {
46      Self::Sha1 => f.write_str("SHA1"),
47      Self::Sha256 => f.write_str("SHA256"),
48      Self::Sha512 => f.write_str("SHA512"),
49    }
50  }
51}