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
|
use axum::{
extract::{Form, State},
http::StatusCode,
response::{IntoResponse, Redirect, Response},
routing::post,
Router,
};
use crate::{app::App, clock::RequestedAt, error::InternalError};
use super::{app, extract::IdentityToken};
pub fn router() -> Router<App> {
Router::new()
.route("/login", post(on_login))
.route("/logout", post(on_logout))
}
#[derive(serde::Deserialize)]
struct LoginRequest {
name: String,
password: String,
}
async fn on_login(
State(app): State<App>,
RequestedAt(now): RequestedAt,
identity: IdentityToken,
Form(form): Form<LoginRequest>,
) -> Result<LoginSuccess, LoginError> {
let token = app
.logins()
.login(&form.name, &form.password, now)
.await
.map_err(LoginError)?;
let identity = identity.set(&token);
Ok(LoginSuccess(identity))
}
struct LoginSuccess(IdentityToken);
impl IntoResponse for LoginSuccess {
fn into_response(self) -> Response {
let Self(identity) = self;
(identity, Redirect::to("/")).into_response()
}
}
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()
}
app::LoginError::DatabaseError(error) => InternalError::from(error).into_response(),
app::LoginError::PasswordHashError(error) => InternalError::from(error).into_response(),
}
}
}
async fn on_logout(
State(app): State<App>,
identity: IdentityToken,
) -> Result<impl IntoResponse, InternalError> {
if let Some(secret) = identity.secret() {
app.logins().logout(secret).await?;
}
let identity = identity.clear();
Ok((identity, Redirect::to("/")))
}
|