Skip to main content

fastauth_core/
mail.rs

1//! Auth emails. A `Mailer` turns each typed email into a message.
2
3use std::any::TypeId;
4use std::fmt;
5use std::future::Future;
6use std::pin::Pin;
7use std::sync::{Arc, Mutex};
8
9#[derive(Clone, Debug, PartialEq, Eq)]
10pub struct VerifyEmail {
11    pub to: String,
12    pub name: String,
13    pub url: String,
14    pub token: String,
15}
16
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct ResetPassword {
19    pub to: String,
20    pub name: String,
21    pub url: String,
22    pub token: String,
23}
24
25/// An email from a plugin (OTP codes, magic links, invitations).
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct PluginEmail {
28    pub kind: &'static str,
29    pub to: String,
30    pub subject: String,
31    pub text: String,
32    pub url: Option<String>,
33    pub code: Option<String>,
34}
35
36#[derive(Clone, Debug, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum AuthEmail {
39    VerifyEmail(VerifyEmail),
40    ResetPassword(ResetPassword),
41    Plugin(PluginEmail),
42}
43
44impl AuthEmail {
45    pub fn to(&self) -> &str {
46        match self {
47            AuthEmail::VerifyEmail(e) => &e.to,
48            AuthEmail::ResetPassword(e) => &e.to,
49            AuthEmail::Plugin(e) => &e.to,
50        }
51    }
52
53    /// A plain-text subject and body, for mailers without templates.
54    pub fn default_text(&self, app_name: &str) -> (String, String) {
55        match self {
56            AuthEmail::VerifyEmail(e) => (
57                format!("Verify your email for {app_name}"),
58                format!("Hi {},\n\nConfirm your email address: {}\n", e.name, e.url),
59            ),
60            AuthEmail::ResetPassword(e) => (
61                format!("Reset your {app_name} password"),
62                format!(
63                    "Hi {},\n\nReset your password: {}\n\nIgnore this email if you didn't ask.\n",
64                    e.name, e.url
65                ),
66            ),
67            AuthEmail::Plugin(e) => (e.subject.clone(), e.text.clone()),
68        }
69    }
70}
71
72#[derive(Debug, thiserror::Error)]
73#[error("sending email failed: {0}")]
74pub struct MailError(pub String);
75
76pub trait Mailer: Send + Sync + 'static {
77    fn send(&self, email: AuthEmail) -> impl Future<Output = Result<(), MailError>> + Send;
78}
79
80pub(crate) trait DynMailer: Send + Sync {
81    fn send(
82        &self,
83        email: AuthEmail,
84    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + '_>>;
85
86    /// Whether this is one of the built-in mailers that do no I/O (`MemoryMailer`,
87    /// `LogMailer`), so sending inline costs nothing and reveals nothing.
88    fn in_process(&self) -> bool;
89}
90
91impl<M: Mailer> DynMailer for M {
92    fn send(
93        &self,
94        email: AuthEmail,
95    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + '_>> {
96        Box::pin(Mailer::send(self, email))
97    }
98
99    fn in_process(&self) -> bool {
100        let id = TypeId::of::<M>();
101        id == TypeId::of::<MemoryMailer>() || id == TypeId::of::<LogMailer>()
102    }
103}
104
105/// Sends `email` without making the request wait for the mailer, so a route answers in the
106/// same time whether or not it sent anything. The send runs on tokio's blocking pool, which
107/// keeps a mailer that blocks off the async workers. A failed send is logged, since there's
108/// no request left to answer.
109///
110/// `MemoryMailer` and `LogMailer` send inline: they take no time, and tests can read
111/// `MemoryMailer` as soon as the response arrives.
112pub(crate) async fn send_in_background(mailer: Arc<dyn DynMailer>, email: AuthEmail) {
113    let kind = match &email {
114        AuthEmail::VerifyEmail(_) => "verify-email",
115        AuthEmail::ResetPassword(_) => "reset-password",
116        AuthEmail::Plugin(e) => e.kind,
117    };
118    if mailer.in_process() {
119        if let Err(err) = mailer.send(email).await {
120            tracing::error!(kind, error = %err, "fastauth could not send an email");
121        }
122        return;
123    }
124    let runtime = tokio::runtime::Handle::current();
125    tokio::task::spawn_blocking(move || {
126        if let Err(err) = runtime.block_on(mailer.send(email)) {
127            tracing::error!(kind, error = %err, "fastauth could not send an email");
128        }
129    });
130}
131
132/// Logs emails instead of sending them. For development.
133#[derive(Clone, Debug, Default)]
134pub struct LogMailer;
135
136impl Mailer for LogMailer {
137    async fn send(&self, email: AuthEmail) -> Result<(), MailError> {
138        let (subject, body) = email.default_text("fastauth");
139        tracing::info!(to = email.to(), %subject, %body, "fastauth email (LogMailer, not sent)");
140        Ok(())
141    }
142}
143
144/// Keeps every email in memory. For tests.
145#[derive(Clone, Default)]
146pub struct MemoryMailer {
147    sent: Arc<Mutex<Vec<AuthEmail>>>,
148}
149
150impl fmt::Debug for MemoryMailer {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        write!(f, "MemoryMailer({} sent)", self.sent.lock().unwrap().len())
153    }
154}
155
156impl MemoryMailer {
157    pub fn new() -> Self {
158        Self::default()
159    }
160
161    pub fn sent(&self) -> Vec<AuthEmail> {
162        self.sent.lock().unwrap().clone()
163    }
164
165    pub fn last(&self) -> Option<AuthEmail> {
166        self.sent.lock().unwrap().last().cloned()
167    }
168}
169
170impl Mailer for MemoryMailer {
171    async fn send(&self, email: AuthEmail) -> Result<(), MailError> {
172        self.sent.lock().unwrap().push(email);
173        Ok(())
174    }
175}