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
|
use axum::{
extract::{Json, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::{get, post},
Router,
};
use crate::{app::App, clock::RequestedAt, error::InternalError, repo::login::Login};
use super::{app, extract::IdentityToken};
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: String,
}
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))
}
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 => InternalError::from(other).into_response(),
}
}
}
#[derive(serde::Deserialize)]
struct LogoutRequest {}
async fn on_logout(
State(app): State<App>,
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() {
app.logins().logout(secret).await.map_err(LogoutError)?;
}
let identity = identity.clear();
Ok((identity, StatusCode::NO_CONTENT))
}
struct LogoutError(app::ValidateError);
impl IntoResponse for LogoutError {
fn into_response(self) -> Response {
let Self(error) = self;
match error {
error @ app::ValidateError::InvalidToken => {
(StatusCode::UNAUTHORIZED, error.to_string()).into_response()
}
other => InternalError::from(other).into_response(),
}
}
}
|