1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
use sqlx::{sqlite::Sqlite, Transaction};
use super::{password::StoredHash, repo::Provider as _, validate, History, Password};
use crate::{
clock::DateTime,
event::{repo::Provider as _, Broadcaster, Event},
name::Name,
};
pub struct Create<'a> {
name: &'a Name,
password: &'a Password,
created_at: &'a DateTime,
}
impl<'a> Create<'a> {
#[must_use = "dropping a login creation attempt is likely a mistake"]
pub fn begin(name: &'a Name, password: &'a Password, created_at: &'a DateTime) -> Self {
Self {
name,
password,
created_at,
}
}
#[must_use = "dropping a login creation attempt is likely a mistake"]
pub fn validate(self) -> Result<Validated<'a>, Error> {
let Self {
name,
password,
created_at,
} = self;
if !validate::name(name) {
return Err(Error::InvalidName(name.clone()));
}
let password_hash = password.hash()?;
Ok(Validated {
name,
password_hash,
created_at,
})
}
}
pub struct Validated<'a> {
name: &'a Name,
password_hash: StoredHash,
created_at: &'a DateTime,
}
impl<'a> Validated<'a> {
#[must_use = "dropping a login creation attempt is likely a mistake"]
pub async fn store<'c>(self, tx: &mut Transaction<'c, Sqlite>) -> Result<Stored, sqlx::Error> {
let Self {
name,
password_hash,
created_at,
} = self;
let created = tx.sequence().next(created_at).await?;
let login = tx.logins().create(name, &password_hash, &created).await?;
Ok(Stored { login })
}
}
pub struct Stored {
login: History,
}
impl Stored {
#[must_use = "dropping a login creation attempt is likely a mistake"]
pub fn publish(self, events: &Broadcaster) -> History {
let Self { login } = self;
events.broadcast(login.events().map(Event::from).collect::<Vec<_>>());
login
}
pub fn login(&self) -> &History {
&self.login
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("invalid login name: {0}")]
InvalidName(Name),
#[error(transparent)]
PasswordHash(#[from] password_hash::Error),
}
|