Skip to main content

sunday_slate/invites/
service.rs

1use uuid::Uuid;
2
3use crate::auth::password;
4use crate::invites::model::{InviteLink, InviteToken};
5use crate::invites::store;
6use crate::leagues::League;
7use crate::mail::Mailer;
8use crate::{AppError, Db};
9
10/// A fresh secret and the hash to store for it. Only the secret leaves this
11/// module — the invite row keeps the hash, so a link is unrecoverable once the
12/// caller drops it.
13fn mint_secret() -> (String, String) {
14    let secret = Uuid::new_v4().to_string();
15    let hash = password::hash(&secret);
16    (secret, hash)
17}
18
19/// The URL a visitor follows to accept an invite.
20fn accept_link(base_url: &str, token: &InviteToken) -> String {
21    format!("{base_url}/invite?token={token}")
22}
23async fn send_invite_email(
24    mailer: &Mailer,
25    email: &str,
26    league: &League,
27    link: &str,
28) -> Result<(), AppError> {
29    let message = crate::mail::render::invite_email(
30        mailer.from(),
31        email,
32        &format!("You're invited to {}", league.name),
33        link,
34        &league.name,
35    )?;
36    mailer.send(message).await?;
37    Ok(())
38}
39
40/// A newly created invite: its row id, and the accept link that just went out
41/// by email. The link is returned rather than discarded so the commissioner can
42/// be shown it immediately — reading it back later is impossible.
43pub struct SentInvite {
44    pub id: i64,
45    pub link: String,
46}
47
48/// Mint an invite token for `email` in `league`, persist it, and send the email.
49/// Awaited (not spawned): the commissioner gets synchronous confirmation, and the
50/// new invite is durable before the handler redirects to the list.
51pub async fn send_invite(
52    db: &Db,
53    mailer: &Mailer,
54    base_url: &str,
55    league: &League,
56    email: &str,
57) -> Result<SentInvite, AppError> {
58    let (secret, token_hash) = mint_secret();
59    let id = db
60        .write_tx(async |conn| -> Result<i64, sqlx::Error> {
61            store::upsert(conn, league.id, email, &token_hash).await
62        })
63        .await?;
64    let token = InviteToken { id, secret };
65    let link = accept_link(base_url, &token);
66
67    send_invite_email(mailer, email, league, &link).await?;
68    Ok(SentInvite { id, link })
69}
70
71/// Mint a fresh link for an outstanding invite, attempt to email it once, and
72/// show it so the commissioner can also send it by hand — a text message, say.
73///
74/// The stored secret is hashed and cannot be read back, so "show me the link"
75/// necessarily means "mint a new one": this retires whichever link went out
76/// before and restarts the invite's expiry. Email delivery is best effort after
77/// the commit: a failure still returns the fresh link. `None` when the invite
78/// is already accepted, revoked, or belongs to another league.
79pub async fn invite_link(
80    db: &Db,
81    mailer: &Mailer,
82    base_url: &str,
83    league: &League,
84    invite_id: i64,
85) -> Result<Option<InviteLink>, AppError> {
86    let (secret, token_hash) = mint_secret();
87    let league_id = league.id;
88    let Some(email) = db
89        .write_tx(async |conn| -> Result<Option<String>, sqlx::Error> {
90            store::reissue(&mut *conn, invite_id, league_id, &token_hash).await
91        })
92        .await?
93    else {
94        return Ok(None);
95    };
96
97    let token = InviteToken {
98        id: invite_id,
99        secret,
100    };
101    let link = accept_link(base_url, &token);
102    match send_invite_email(mailer, &email, league, &link).await {
103        Ok(()) => Ok(Some(InviteLink::Reissued(link))),
104        Err(err) => {
105            tracing::warn!(invite_id, error = %err, "Failed to email regenerated invite");
106            Ok(Some(InviteLink::ReissuedEmailFailed(link)))
107        }
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114    use crate::leagues;
115    use crate::tests::factories;
116    use crate::tests::factories::InviteOptions;
117    use sqlx::SqlitePool;
118
119    #[sqlx::test]
120    async fn send_invite_names_the_league_in_the_subject(pool: SqlitePool) {
121        let league = leagues::store::create(&pool, "Sunday Funday")
122            .await
123            .expect("seed league");
124        let mailer = Mailer::capture("Sunday Slate <no-reply@example.com>");
125        let db = Db::test(pool.clone());
126
127        send_invite(
128            &db,
129            &mailer,
130            "http://localhost:3000",
131            &league,
132            "invitee@example.com",
133        )
134        .await
135        .expect("send");
136
137        let sent = mailer.all();
138        assert_eq!(sent[0].subject, "You're invited to Sunday Funday");
139    }
140
141    #[sqlx::test]
142    async fn invite_link_mints_a_link_that_works_and_retires_the_old_one(pool: SqlitePool) {
143        let league = leagues::store::create(&pool, "Sunday Funday")
144            .await
145            .expect("seed league");
146        let existing = factories::invite(
147            &pool,
148            InviteOptions {
149                league: Some(league.clone()),
150                ..Default::default()
151            },
152        )
153        .await;
154        let db = Db::test(pool.clone());
155        let mailer = Mailer::capture("Sunday Slate <no-reply@example.com>");
156        let outcome = invite_link(&db, &mailer, "http://localhost:3000", &league, existing.id)
157            .await
158            .expect("link")
159            .expect("invite is outstanding");
160        let link = outcome.url();
161
162        let fresh = link
163            .strip_prefix("http://localhost:3000/invite?token=")
164            .expect("link shape");
165        assert!(
166            store::verify(&db, fresh).await.expect("verify").is_some(),
167            "the copied link must accept the invite"
168        );
169        assert!(
170            store::verify(&db, &existing.token())
171                .await
172                .expect("verify")
173                .is_none(),
174            "the previously sent link must stop working"
175        );
176        let sent = mailer.all();
177        assert_eq!(sent.len(), 1, "regeneration sends one invite email");
178        assert_eq!(sent[0].to, existing.email);
179        assert!(sent[0].html.contains(link));
180        assert!(sent[0].text.contains(link));
181    }
182
183    #[sqlx::test]
184    async fn invite_link_declines_an_invite_from_another_league(pool: SqlitePool) {
185        let mine = leagues::store::create(&pool, "Mine")
186            .await
187            .expect("seed league");
188        let theirs = leagues::store::create(&pool, "Theirs")
189            .await
190            .expect("seed league");
191        let existing = factories::invite(
192            &pool,
193            InviteOptions {
194                league: Some(theirs),
195                ..Default::default()
196            },
197        )
198        .await;
199        let db = Db::test(pool.clone());
200
201        assert!(
202            invite_link(
203                &db,
204                &Mailer::capture("Sunday Slate <no-reply@example.com>"),
205                "http://localhost:3000",
206                &mine,
207                existing.id,
208            )
209            .await
210            .expect("link")
211            .is_none()
212        );
213    }
214
215    #[sqlx::test]
216    async fn send_invite_persists_and_captures_email(pool: SqlitePool) {
217        let league = leagues::store::create(&pool, "Sunday Funday")
218            .await
219            .expect("seed league");
220        let mailer = Mailer::capture("Sunday Slate <no-reply@example.com>");
221
222        let db = Db::test(pool.clone());
223        send_invite(
224            &db,
225            &mailer,
226            "http://localhost:3000",
227            &league,
228            "Invitee@Example.com",
229        )
230        .await
231        .expect("send");
232
233        let email: String = sqlx::query_scalar("SELECT email FROM invites")
234            .fetch_one(&pool)
235            .await
236            .expect("invite row");
237        assert_eq!(email, "invitee@example.com");
238
239        let sent = mailer.all();
240        assert_eq!(sent.len(), 1);
241        assert!(sent[0].html.contains("/invite?token="));
242    }
243}