-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
343 lines (303 loc) · 9.66 KB
/
lib.rs
File metadata and controls
343 lines (303 loc) · 9.66 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! Provides the [`AuthDomainService`], the entry point for users,
//! authentication, and authorization logic.
use axum_login::AuthUser as AxumLoginAuthUser;
pub use axum_login::AuthnBackend;
use db::{
Database, FetchModelByIndexError, FetchModelError, PatchModelError,
kv::LaxSlug,
};
use miette::{IntoDiagnostic, miette};
use models::{
AuthUser, Org, OrgIdent, User, UserAuthCredentials,
UserSubmittedAuthCredentials, UserUniqueIndexSelector,
dvf::{EitherSlug, EmailAddress, HumanName},
model::RecordId,
};
use tracing::instrument;
/// The authentication session type.
pub type AuthSession = axum_login::AuthSession<AuthDomainService>;
/// A dynamic [`AuthDomainService`] trait object.
#[derive(Clone, Debug)]
pub struct AuthDomainService {
org_repo: Database<Org>,
user_repo: Database<User>,
}
impl AuthDomainService {
/// Creates a new [`AuthDomainService`].
#[must_use]
pub fn new(org_repo: Database<Org>, user_repo: Database<User>) -> Self {
Self {
org_repo,
user_repo,
}
}
}
/// An error that occurs during user creation.
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
pub enum CreateUserError {
/// Indicates that the user's email address is already in use.
#[error("The email address is already in use: \"{0}\"")]
EmailAlreadyUsed(EmailAddress),
/// Indicates than an error occurred while hashing the password.
#[error("Failed to hash password")]
PasswordHashing(miette::Report),
/// Indicates that an error occurred while creating the user.
#[error("Failed to create the user")]
CreateError(miette::Report),
/// Indicates that an error occurred while fetching users by index.
#[error("Failed to fetch users by index")]
FetchByIndexError(#[from] FetchModelByIndexError),
}
/// An error that occurs during user authentication.
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
pub enum AuthenticationError {
/// Indicates that an error occurred while fetching users.
#[error("Failed to fetch user")]
FetchError(#[from] FetchModelError),
/// Indicates that an error occurred while fetching users by index.
#[error("Failed to fetch user by index")]
FetchByIndexError(#[from] FetchModelByIndexError),
/// Indicates than an error occurred while hashing the password.
#[error("Failed to hash password")]
PasswordHashing(miette::Report),
}
/// An error that occurs while updating a user's active org.
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
pub enum UpdateActiveOrgError {
/// Indicates that an error occurred while fetching the user.
#[error("Failed to fetch user")]
FetchError(#[from] FetchModelError),
/// Indicates that the user does not exist.
#[error("Failed to find user: {0}")]
MissingUser(RecordId<User>),
/// Indicates that the org supplied could not be switched to.
#[error("Failed to switch to org: {0}")]
InvalidOrg(RecordId<Org>),
/// Indicates that an error occurred while patching the user record.
#[error("Failed to patch user")]
PatchError(#[from] PatchModelError),
}
impl AuthDomainService {
/// Fetch a [`User`] by ID.
#[instrument(skip(self))]
pub async fn fetch_user_by_id(
&self,
id: RecordId<User>,
) -> Result<Option<User>, FetchModelError> {
self.user_repo.fetch_model_by_id(id).await
}
/// Fetch a [`User`] by [`EmailAddress`](EmailAddress).
#[instrument(skip(self))]
pub async fn fetch_user_by_email(
&self,
email: EmailAddress,
) -> Result<Option<User>, FetchModelByIndexError> {
self
.user_repo
.fetch_model_by_unique_index(
UserUniqueIndexSelector::Email,
EitherSlug::Lax(LaxSlug::new(email.as_ref())),
)
.await
}
/// Switch a [`User`]'s active org.
#[instrument(skip(self))]
pub async fn switch_active_org(
&self,
user: RecordId<User>,
new_active_org: RecordId<Org>,
) -> Result<RecordId<Org>, UpdateActiveOrgError> {
let user = self
.user_repo
.fetch_model_by_id(user)
.await?
.ok_or(UpdateActiveOrgError::MissingUser(user))?;
let new_index = user
.iter_orgs()
.position(|o| o == new_active_org)
.ok_or(UpdateActiveOrgError::InvalidOrg(new_active_org))?;
self
.user_repo
.patch_model(user.id, User {
active_org_index: new_index as _,
..user
})
.await?;
Ok(new_active_org)
}
/// Sign up a [`User`].
#[instrument(skip(self))]
pub async fn user_signup(
&self,
name: HumanName,
email: EmailAddress,
auth: UserSubmittedAuthCredentials,
) -> Result<User, CreateUserError> {
use argon2::PasswordHasher;
if self.fetch_user_by_email(email.clone()).await?.is_some() {
return Err(CreateUserError::EmailAlreadyUsed(email));
}
let auth: UserAuthCredentials = match auth {
UserSubmittedAuthCredentials::Password { password } => {
let salt = argon2::password_hash::SaltString::generate(
&mut argon2::password_hash::rand_core::OsRng,
);
let argon = argon2::Argon2::default();
let password_hash = models::PasswordHash(
argon
.hash_password(password.as_bytes(), &salt)
.map_err(|e| {
CreateUserError::PasswordHashing(miette!(
"failed to hash password: {e}"
))
})?
.to_string(),
);
UserAuthCredentials::Password { password_hash }
}
};
let user_id = RecordId::new();
let org = Org {
id: RecordId::new(),
org_ident: OrgIdent::UserOrg(user_id),
};
let user = User {
id: user_id,
personal_org: org.id,
orgs: Vec::new(),
name,
email,
auth,
active_org_index: 0,
};
self
.org_repo
.create_model(org)
.await
.into_diagnostic()
.map_err(CreateUserError::CreateError)?;
self
.user_repo
.create_model(user)
.await
.into_diagnostic()
.map_err(CreateUserError::CreateError)
}
/// Authenticate a [`User`].
#[instrument(skip(self))]
pub async fn user_authenticate(
&self,
email: EmailAddress,
creds: UserSubmittedAuthCredentials,
) -> Result<Option<User>, AuthenticationError> {
use argon2::PasswordVerifier;
let Some(user) = self.fetch_user_by_email(email).await? else {
return Ok(None);
};
match (creds, user.auth.clone()) {
(
UserSubmittedAuthCredentials::Password { password, .. },
UserAuthCredentials::Password { password_hash, .. },
) => {
let password_hash = argon2::PasswordHash::new(&password_hash.0)
.map_err(|e| {
AuthenticationError::PasswordHashing(miette!(
"failed to parse password hash: {e}"
))
})?;
let argon = argon2::Argon2::default();
let correct =
(match argon.verify_password(password.as_bytes(), &password_hash) {
Ok(()) => Ok(true),
Err(argon2::password_hash::Error::Password) => Ok(false),
Err(e) => Err(e),
})
.map_err(|e| {
AuthenticationError::PasswordHashing(miette!(
"failed to verify password against hash: {e}"
))
})?;
Ok(correct.then_some(user))
}
}
}
}
impl AuthnBackend for AuthDomainService {
type Credentials = (EmailAddress, UserSubmittedAuthCredentials);
type Error = AuthenticationError;
type User = AuthUser;
async fn authenticate(
&self,
creds: Self::Credentials,
) -> Result<Option<Self::User>, Self::Error> {
self
.user_authenticate(creds.0, creds.1)
.await
.map(|u| u.map(Into::into))
}
async fn get_user(
&self,
id: &<Self::User as AxumLoginAuthUser>::Id,
) -> Result<Option<Self::User>, Self::Error> {
self
.fetch_user_by_id(*id)
.await
.map(|u| u.map(Into::into))
.map_err(Into::into)
}
}
#[cfg(test)]
mod tests {
use models::dvf::{EmailAddress, HumanName};
use super::*;
#[tokio::test]
async fn test_user_signup() {
let org_repo = Database::new_mock();
let user_repo = Database::new_mock();
let service = AuthDomainService::new(org_repo, user_repo);
let name = HumanName::try_new("Test User 1").unwrap();
let email = EmailAddress::try_new("test@example.com").unwrap();
let creds = UserSubmittedAuthCredentials::Password {
password: "hunter42".to_string(),
};
let user = service
.user_signup(name, email.clone(), creds.clone())
.await
.unwrap();
assert_eq!(user.email, email);
dbg!(&service);
let name = HumanName::try_new("Test User 2").unwrap();
let user2 = service
.user_signup(name, email.clone(), creds.clone())
.await;
assert!(matches!(user2, Err(CreateUserError::EmailAlreadyUsed(_))));
}
#[tokio::test]
async fn test_user_authenticate() {
let org_repo = Database::new_mock();
let user_repo = Database::new_mock();
let service = AuthDomainService::new(org_repo, user_repo);
let name = HumanName::try_new("Test User 1").unwrap();
let email = EmailAddress::try_new("test@example.com").unwrap();
let creds = UserSubmittedAuthCredentials::Password {
password: "hunter42".to_string(),
};
let user = service
.user_signup(name, email.clone(), creds.clone())
.await
.unwrap();
assert_eq!(user.email, email);
let auth_user = service
.user_authenticate(email.clone(), creds)
.await
.unwrap();
assert_eq!(auth_user, Some(user));
let wrong_email = EmailAddress::try_new("untest@example.com").unwrap();
let creds = UserSubmittedAuthCredentials::Password {
password: "hunter42".to_string(),
};
let auth_user =
service.user_authenticate(wrong_email, creds).await.unwrap();
assert_eq!(auth_user, None);
}
}