alibi_plugins/email_otp/
storage.rs1use crate::token_crypto::{decrypt_with_config, encrypt_with_config, hash_token};
2use alibi_core::{AuthError, AuthResult};
3use async_trait::async_trait;
4use std::sync::Arc;
5
6#[async_trait]
9pub trait EmailOtpCodec: Send + Sync {
10 async fn store(&self, otp: &str) -> AuthResult<String>;
11 async fn verify(&self, stored: &str, otp: &str) -> AuthResult<bool>;
12 async fn retrieve(&self, stored: &str) -> AuthResult<Option<String>>;
13}
14
15#[derive(Clone)]
16pub enum EmailOtpStorage {
17 Plain,
18 Hashed,
19 Encrypted,
20 Custom(Arc<dyn EmailOtpCodec>),
21}
22
23impl std::fmt::Debug for EmailOtpStorage {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 match self {
26 Self::Plain => f.write_str("EmailOtpStorage::Plain"),
27 Self::Hashed => f.write_str("EmailOtpStorage::Hashed"),
28 Self::Encrypted => f.write_str("EmailOtpStorage::Encrypted"),
29 Self::Custom(..) => f.write_str("EmailOtpStorage::Custom"),
30 }
31 }
32}
33
34impl EmailOtpStorage {
35 pub(super) async fn store(
36 &self,
37 otp: &str,
38 secret: &alibi_core::AuthConfig,
39 ) -> AuthResult<String> {
40 match self {
41 Self::Plain => Ok(otp.to_owned()),
42 Self::Hashed => Ok(hash_token(otp)),
43 Self::Encrypted => encrypt_with_config(otp, secret),
44 Self::Custom(codec) => codec.store(otp).await,
45 }
46 }
47
48 pub(super) async fn verify(
49 &self,
50 stored: &str,
51 otp: &str,
52 secret: &alibi_core::AuthConfig,
53 ) -> AuthResult<bool> {
54 match self {
55 Self::Plain => Ok(constant_time_equal(stored, otp)),
56 Self::Hashed => Ok(constant_time_equal(stored, &hash_token(otp))),
57 Self::Encrypted => Ok(constant_time_equal(
58 &decrypt_with_config(stored, secret)?,
59 otp,
60 )),
61 Self::Custom(codec) => codec.verify(stored, otp).await,
62 }
63 }
64
65 pub(super) async fn retrieve(
66 &self,
67 stored: &str,
68 secret: &alibi_core::AuthConfig,
69 ) -> AuthResult<Option<String>> {
70 let plain = match self {
71 Self::Plain => Some(stored.to_owned()),
72 Self::Hashed => None,
73 Self::Encrypted => Some(decrypt_with_config(stored, secret)?),
74 Self::Custom(codec) => codec.retrieve(stored).await?,
75 };
76 plain.map(Some).ok_or_else(|| {
77 AuthError::bad_request("OTP is hashed, cannot return the plain text OTP")
78 })
79 }
80
81 pub(super) async fn reusable(
82 &self,
83 stored: &str,
84 secret: &alibi_core::AuthConfig,
85 ) -> AuthResult<Option<String>> {
86 match self {
87 Self::Hashed => Ok(None),
88 Self::Custom(codec) => codec.retrieve(stored).await,
89 Self::Plain | Self::Encrypted => self.retrieve(stored, secret).await,
90 }
91 }
92}
93
94fn constant_time_equal(left: &str, right: &str) -> bool {
95 if left.len() != right.len() {
96 return false;
97 }
98 left.bytes()
99 .zip(right.bytes())
100 .fold(0u8, |difference, (a, b)| difference | (a ^ b))
101 == 0
102}