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
|
use axum::{
extract::{Json, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::{get, post},
Router,
};
use crate::{
app::App, clock::RequestedAt, error::Internal, password::Password, repo::login::Login,
};
use super::{app, extract::IdentityToken};
#[cfg(test)]
mod test;
pub fn router() -> Router<App> {
Router::new()
.route("/api/boot", get(boot))
.route("/api/auth/login", post(on_login))
.route("/api/auth/logout", post(on_logout))
}
async fn boot(login: Login) -> Boot {
Boot { login }
}
#[derive(serde::Serialize)]
struct Boot {
login: Login,
}
impl IntoResponse for Boot {
fn into_response(self) -> Response {
Json(self).into_response()
}
}
#[derive(serde::Deserialize)]
struct LoginRequest {
name: String,
password: Password,
}
async fn on_login(
State(app): State<App>,
RequestedAt(now): RequestedAt,
identity: IdentityToken,
Json(request): Json<LoginRequest>,
) -> Result<(IdentityToken, StatusCode), LoginError> {
let token = app
.logins()
.login(&request.name, &request.password, &now)
.await
.map_err(LoginError)?;
let identity = identity.set(token);
Ok((identity, StatusCode::NO_CONTENT))
}
#[derive(Debug)]
struct LoginError(app::LoginError);
impl IntoResponse for LoginError {
fn into_response(self) -> Response {
let Self(error) = self;
match error {
app::LoginError::Rejected => {
(StatusCode::UNAUTHORIZED, "invalid name or password").into_response()
}
other => Internal::from(other).into_response(),
}
}
}
#[derive(serde::Deserialize)]
struct LogoutRequest {}
async fn on_logout(
State(app): State<App>,
RequestedAt(now): RequestedAt,
identity: IdentityToken,
// This forces the only valid request to be `{}`, and not the infinite
// variation allowed when there's no body extractor.
Json(LogoutRequest {}): Json<LogoutRequest>,
) -> Result<(IdentityToken, StatusCode), LogoutError> {
if let Some(secret) = identity.secret() {
let (token, _) = app.logins().validate(&secret, &now).await?;
app.logins().logout(&token).await?;
}
let identity = identity.clear();
Ok((identity, StatusCode::NO_CONTENT))
}
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
enum LogoutError {
ValidateError(#[from] app::ValidateError),
DatabaseError(#[from] sqlx::Error),
}
impl IntoResponse for LogoutError {
fn into_response(self) -> Response {
match self {
error @ Self::ValidateError(app::ValidateError::InvalidToken) => {
(StatusCode::UNAUTHORIZED, error.to_string()).into_response()
}
other => Internal::from(other).into_response(),
}
}
}
|