Skip to main content

aurelin_fortify/
email_verification.rs

1use std::time::Duration;
2
3use aurelin_framework::{
4    auth::digest_token,
5    signed_url::{SignedUrlError, TemporarySignedUrl},
6};
7use thiserror::Error;
8
9#[derive(Clone, Debug)]
10pub struct EmailVerification {
11    signed_urls: TemporarySignedUrl,
12    lifetime_seconds: i64,
13}
14
15#[derive(Clone, Copy, Debug)]
16pub struct EmailVerificationRequest<'a> {
17    pub user_id: i64,
18    pub email: &'a str,
19    pub email_hash: &'a str,
20    pub expires: i64,
21    pub signature: &'a str,
22}
23
24impl EmailVerification {
25    pub fn new(application_key: &[u8]) -> Result<Self, EmailVerificationError> {
26        Ok(Self {
27            signed_urls: TemporarySignedUrl::new(application_key)?,
28            lifetime_seconds: Duration::from_secs(60 * 60).as_secs().cast_signed(),
29        })
30    }
31
32    pub fn url(&self, user_id: i64, email: &str, now: i64) -> Result<String, EmailVerificationError> {
33        let email_hash = digest_token(email);
34        let expires = now + self.lifetime_seconds;
35        let unsigned = format!("/email/verify/{user_id}/{email_hash}?expires={expires}");
36        let signature = self.signed_urls.sign(&unsigned)?;
37        Ok(format!("{unsigned}&signature={signature}"))
38    }
39
40    pub fn verify(&self, request: EmailVerificationRequest<'_>, now: i64) -> Result<bool, EmailVerificationError> {
41        if request.expires < now || request.email_hash != digest_token(request.email) {
42            return Ok(false);
43        }
44        let unsigned = format!("/email/verify/{}/{}?expires={}", request.user_id, request.email_hash, request.expires);
45        Ok(self.signed_urls.verify(&unsigned, request.signature)?)
46    }
47}
48
49#[derive(Debug, Error)]
50pub enum EmailVerificationError {
51    #[error(transparent)]
52    SignedUrl(#[from] SignedUrlError),
53}