Skip to main content

fastauth_core/
mail.rs

1//! Auth emails. A `Mailer` turns each typed email into a message.
2
3use std::fmt;
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::{Arc, Mutex};
7
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct VerifyEmail {
10    pub to: String,
11    pub name: String,
12    pub url: String,
13    pub token: String,
14}
15
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct ResetPassword {
18    pub to: String,
19    pub name: String,
20    pub url: String,
21    pub token: String,
22}
23
24/// An email from a plugin (OTP codes, magic links, invitations).
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct PluginEmail {
27    pub kind: &'static str,
28    pub to: String,
29    pub subject: String,
30    pub text: String,
31    pub url: Option<String>,
32    pub code: Option<String>,
33}
34
35#[derive(Clone, Debug, PartialEq, Eq)]
36#[non_exhaustive]
37pub enum AuthEmail {
38    VerifyEmail(VerifyEmail),
39    ResetPassword(ResetPassword),
40    Plugin(PluginEmail),
41}
42
43impl AuthEmail {
44    pub fn to(&self) -> &str {
45        match self {
46            AuthEmail::VerifyEmail(e) => &e.to,
47            AuthEmail::ResetPassword(e) => &e.to,
48            AuthEmail::Plugin(e) => &e.to,
49        }
50    }
51
52    /// A plain-text subject and body, for mailers without templates.
53    pub fn default_text(&self, app_name: &str) -> (String, String) {
54        match self {
55            AuthEmail::VerifyEmail(e) => (
56                format!("Verify your email for {app_name}"),
57                format!("Hi {},\n\nConfirm your email address: {}\n", e.name, e.url),
58            ),
59            AuthEmail::ResetPassword(e) => (
60                format!("Reset your {app_name} password"),
61                format!(
62                    "Hi {},\n\nReset your password: {}\n\nIgnore this email if you didn't ask.\n",
63                    e.name, e.url
64                ),
65            ),
66            AuthEmail::Plugin(e) => (e.subject.clone(), e.text.clone()),
67        }
68    }
69}
70
71#[derive(Debug, thiserror::Error)]
72#[error("sending email failed: {0}")]
73pub struct MailError(pub String);
74
75pub trait Mailer: Send + Sync + 'static {
76    fn send(&self, email: AuthEmail) -> impl Future<Output = Result<(), MailError>> + Send;
77}
78
79pub(crate) trait DynMailer: Send + Sync {
80    fn send(
81        &self,
82        email: AuthEmail,
83    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + '_>>;
84}
85
86impl<M: Mailer> DynMailer for M {
87    fn send(
88        &self,
89        email: AuthEmail,
90    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + '_>> {
91        Box::pin(Mailer::send(self, email))
92    }
93}
94
95/// Logs emails instead of sending them. For development.
96#[derive(Clone, Debug, Default)]
97pub struct LogMailer;
98
99impl Mailer for LogMailer {
100    async fn send(&self, email: AuthEmail) -> Result<(), MailError> {
101        let (subject, body) = email.default_text("fastauth");
102        tracing::info!(to = email.to(), %subject, %body, "fastauth email (LogMailer, not sent)");
103        Ok(())
104    }
105}
106
107/// Keeps every email in memory. For tests.
108#[derive(Clone, Default)]
109pub struct MemoryMailer {
110    sent: Arc<Mutex<Vec<AuthEmail>>>,
111}
112
113impl fmt::Debug for MemoryMailer {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        write!(f, "MemoryMailer({} sent)", self.sent.lock().unwrap().len())
116    }
117}
118
119impl MemoryMailer {
120    pub fn new() -> Self {
121        Self::default()
122    }
123
124    pub fn sent(&self) -> Vec<AuthEmail> {
125        self.sent.lock().unwrap().clone()
126    }
127
128    pub fn last(&self) -> Option<AuthEmail> {
129        self.sent.lock().unwrap().last().cloned()
130    }
131}
132
133impl Mailer for MemoryMailer {
134    async fn send(&self, email: AuthEmail) -> Result<(), MailError> {
135        self.sent.lock().unwrap().push(email);
136        Ok(())
137    }
138}