Skip to main content

sunday_slate/invites/
model.rs

1use std::fmt;
2use std::str::FromStr;
3
4use serde::{Deserialize, Serialize};
5use time::PrimitiveDateTime;
6
7/// A row for the commissioner's invite list.
8#[derive(Debug, Clone, sqlx::FromRow)]
9pub struct PendingInvite {
10    pub id: i64,
11    pub email: String,
12    pub expires_at: PrimitiveDateTime,
13    pub accepted_at: Option<PrimitiveDateTime>,
14}
15
16/// A freshly minted accept link and how it was delivered.
17///
18/// The secret behind a link is hashed at rest, so a link exists only in the
19/// response that mints it. The delivery outcome decides what the page tells
20/// the commissioner.
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub enum InviteLink {
23    /// Handed back as the invite was created. The email carries this same
24    /// link, so showing it retires nothing.
25    Issued(String),
26    /// Minted on demand for an invite that already existed. The stored secret
27    /// could not be read back, so this necessarily replaced whatever link went
28    /// out before and sent the new link by email.
29    Reissued(String),
30    /// Minted on demand, but email delivery failed. The commissioner can send
31    /// this replacement link by hand.
32    ReissuedEmailFailed(String),
33}
34
35impl InviteLink {
36    pub fn url(&self) -> &str {
37        match self {
38            Self::Issued(url) | Self::Reissued(url) | Self::ReissuedEmailFailed(url) => url,
39        }
40    }
41
42    /// True when showing this link stopped an earlier one from working.
43    pub fn retires_previous(&self) -> bool {
44        matches!(self, Self::Reissued(_) | Self::ReissuedEmailFailed(_))
45    }
46
47    pub fn email_failed(&self) -> bool {
48        matches!(self, Self::ReissuedEmailFailed(_))
49    }
50}
51
52/// A row of the commissioner's invite list, plus the accept link when one was
53/// just minted for it. `link` is `None` on every row except the one the
54/// commissioner just created or asked to copy.
55pub struct InviteRow {
56    pub invite: PendingInvite,
57    pub link: Option<InviteLink>,
58}
59
60/// An invite token in URL form: `"{id}.{secret}"`. Same shape as `ResetToken`,
61/// but resolves to a league + email rather than a user.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct InviteToken {
64    pub id: i64,
65    pub secret: String,
66}
67
68impl fmt::Display for InviteToken {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        write!(f, "{}.{}", self.id, self.secret)
71    }
72}
73
74impl FromStr for InviteToken {
75    type Err = ();
76
77    fn from_str(s: &str) -> Result<Self, Self::Err> {
78        let (id, secret) = s.split_once('.').ok_or(())?;
79        let id: i64 = id.parse().map_err(|_| ())?;
80        if secret.is_empty() {
81            return Err(());
82        }
83        Ok(InviteToken {
84            id,
85            secret: secret.to_string(),
86        })
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn display_then_parse_roundtrips() {
96        let token = InviteToken {
97            id: 7,
98            secret: "ab-12".to_string(),
99        };
100        let parsed: InviteToken = token.to_string().parse().expect("roundtrip");
101        assert_eq!(parsed, token);
102    }
103
104    #[test]
105    fn parse_rejects_missing_dot() {
106        assert!("nodot".parse::<InviteToken>().is_err());
107    }
108
109    #[test]
110    fn parse_rejects_non_numeric_id() {
111        assert!("abc.secret".parse::<InviteToken>().is_err());
112    }
113
114    #[test]
115    fn parse_rejects_empty_secret() {
116        assert!("7.".parse::<InviteToken>().is_err());
117    }
118}