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
|
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::LoginError, 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<impl IntoResponse, InternalError> {
match app.logins().login(&form.name, &form.password, now).await {
Ok(token) => {
let identity = identity.set(&token);
Ok(LoginResponse::Successful(identity))
}
Err(LoginError::Rejected) => Ok(LoginResponse::Rejected),
Err(other) => Err(other.into()),
}
}
enum LoginResponse {
Rejected,
Successful(IdentityToken),
}
impl IntoResponse for LoginResponse {
fn into_response(self) -> Response {
match self {
Self::Successful(identity) => (identity, Redirect::to("/")).into_response(),
Self::Rejected => {
(StatusCode::UNAUTHORIZED, "invalid name or password").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("/")))
}
|