Skip to main content

aurelin_framework/auth/
password_reset.rs

1use std::{error::Error, future::Future};
2
3use rand::{Rng, distr::Alphanumeric};
4use thiserror::Error;
5
6use super::digest_token;
7
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct StoredPasswordResetToken {
10    pub digest: String,
11    pub created_at: i64,
12}
13
14pub struct ValidatedPasswordReset<'a> {
15    pub email: &'a str,
16    pub expected_digest: String,
17    pub password: &'a str,
18}
19
20pub struct PasswordResetCredentials<'a> {
21    pub email: &'a str,
22    pub token: &'a str,
23    pub password: &'a str,
24}
25
26pub trait PasswordResetRepository: Clone + Send + Sync + 'static {
27    type Error: Error + Send + Sync + 'static;
28
29    fn user_exists(&self, email: &str) -> impl Future<Output = Result<bool, Self::Error>> + Send;
30    fn token(&self, email: &str) -> impl Future<Output = Result<Option<StoredPasswordResetToken>, Self::Error>> + Send;
31    fn replace_token(
32        &self,
33        email: &str,
34        token: StoredPasswordResetToken,
35    ) -> impl Future<Output = Result<(), Self::Error>> + Send;
36    fn delete_token(
37        &self,
38        email: &str,
39        expected_digest: &str,
40    ) -> impl Future<Output = Result<bool, Self::Error>> + Send;
41}
42
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub enum PasswordResetRequest {
45    Sent { token: String },
46    UnknownUser,
47    Throttled,
48}
49
50#[derive(Clone, Debug)]
51pub struct PasswordResetBroker<R> {
52    repository: R,
53    expires_after_seconds: i64,
54    throttle_seconds: i64,
55}
56
57impl<R> PasswordResetBroker<R>
58where
59    R: PasswordResetRepository,
60{
61    pub fn new(repository: R) -> Self {
62        Self { repository, expires_after_seconds: 60 * 60, throttle_seconds: 60 }
63    }
64
65    pub async fn create_token(
66        &self,
67        email: &str,
68        now: i64,
69    ) -> Result<PasswordResetRequest, PasswordResetError<R::Error>> {
70        if !self.repository.user_exists(email).await.map_err(PasswordResetError::Repository)? {
71            return Ok(PasswordResetRequest::UnknownUser);
72        }
73        if self
74            .repository
75            .token(email)
76            .await
77            .map_err(PasswordResetError::Repository)?
78            .is_some_and(|token| token.created_at > now - self.throttle_seconds)
79        {
80            return Ok(PasswordResetRequest::Throttled);
81        }
82        let token: String = rand::rng().sample_iter(Alphanumeric).take(64).map(char::from).collect();
83        self.repository
84            .replace_token(email, StoredPasswordResetToken { digest: digest_token(&token), created_at: now })
85            .await
86            .map_err(PasswordResetError::Repository)?;
87        Ok(PasswordResetRequest::Sent { token })
88    }
89
90    pub async fn validate_reset<'a>(
91        &self,
92        credentials: PasswordResetCredentials<'a>,
93        now: i64,
94    ) -> Result<Option<ValidatedPasswordReset<'a>>, PasswordResetError<R::Error>> {
95        let Some(stored) = self.repository.token(credentials.email).await.map_err(PasswordResetError::Repository)?
96        else {
97            return Ok(None);
98        };
99        let digest = digest_token(credentials.token);
100        if stored.digest != digest || stored.created_at < now - self.expires_after_seconds {
101            return Ok(None);
102        }
103        Ok(Some(ValidatedPasswordReset {
104            email: credentials.email,
105            expected_digest: stored.digest,
106            password: credentials.password,
107        }))
108    }
109
110    pub async fn complete_reset(
111        &self,
112        reset: &ValidatedPasswordReset<'_>,
113    ) -> Result<bool, PasswordResetError<R::Error>> {
114        self.repository.delete_token(reset.email, &reset.expected_digest).await.map_err(PasswordResetError::Repository)
115    }
116}
117
118#[derive(Debug, Error)]
119pub enum PasswordResetError<E>
120where
121    E: Error + 'static,
122{
123    #[error("password reset repository operation failed")]
124    Repository(#[source] E),
125}