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
|
use sqlx::sqlite::SqlitePool;
use super::repo::auth::Provider as _;
use crate::{
clock::DateTime,
error::BoxedError,
password::StoredHash,
repo::{
login::{Login, Provider as _},
token::Provider as _,
},
};
pub struct Logins<'a> {
db: &'a SqlitePool,
}
impl<'a> Logins<'a> {
pub const fn new(db: &'a SqlitePool) -> Self {
Self { db }
}
pub async fn login(
&self,
name: &str,
password: &str,
login_at: DateTime,
) -> Result<Option<String>, BoxedError> {
let mut tx = self.db.begin().await?;
let login = if let Some((login, stored_hash)) = tx.auth().for_name(name).await? {
if stored_hash.verify(password)? {
// Password verified; use the login.
Some(login)
} else {
// Password NOT verified.
None
}
} else {
let password_hash = StoredHash::new(password)?;
Some(tx.logins().create(name, &password_hash).await?)
};
// If `login` is Some, then we have an identity and can issue a token.
// If `login` is None, then neither creating a new login nor
// authenticating an existing one succeeded, and we must reject the
// login attempt.
let token = if let Some(login) = login {
Some(tx.tokens().issue(&login, login_at).await?)
} else {
None
};
tx.commit().await?;
Ok(token)
}
pub async fn validate(
&self,
secret: &str,
used_at: DateTime,
) -> Result<Option<Login>, BoxedError> {
let mut tx = self.db.begin().await?;
tx.tokens().expire(used_at).await?;
let login = tx.tokens().validate(secret, used_at).await?;
tx.commit().await?;
Ok(login)
}
pub async fn logout(&self, secret: &str) -> Result<(), BoxedError> {
let mut tx = self.db.begin().await?;
tx.tokens().revoke(secret).await?;
tx.commit().await?;
Ok(())
}
}
|